Java 方法反射的基本操作

2021-07-23 23:01:25 字數 1210 閱讀 7116

方法的反射:

1.獲取a類中的print(int,int)方法:

①要獲取乙個方法就是獲取類的資訊,獲取類的資訊首先要獲取類的類型別

a a1=new a(); class c= a1.getclass();

②獲取方法 由名稱和引數列表來決定,getmethod獲取的是public方法,getdelcaredmethod獲取自己宣告的方法

method m =c.getmethod(methodname,paramtypes);//paramtypes可以用陣列的形式表示new class,也可以直接列舉類型別

2.方法的反射操作:是用m物件來進行方法呼叫,和a1.print(10,20)呼叫的方法相同m.invoke(a1,new object{10,20})

object o=m.invoke(物件名,引數);//方法如果沒有返回值返回null,如果有返回值返回具體值,引數可用陣列的方式表示,也可以直接列舉,沒有引數就不寫

方法的反射:

1. 方法名稱加引數列表可以唯一確定乙個方法

2. 通過方法物件來實現方法的功能,即把例項物件當成引數傳給方法物件

here is an example:

there is a class a:

class a}

implement the class:

a a = new a();

class c = a.getclass();

method m = c.getmethod("printinfo", string.class, string.class);

//getmethod方法只能獲得public方法

//getdeclaredmethod方法能獲得所有自己宣告的方法

//you can write the above code like following:

method m = c.getmethod("printinfo", new object);

object o = m.invoke(a, "hello ", "world!");//here, o = null

//you can also write like:

object o = m.invoke(a, new object);

//the above code just like:

a.printinfo("hello ","world!");

23 Java入門 反射之方法反射的基本操作

方法的反射 1.獲取a類中的print int,int 方法 要獲取乙個方法就是獲取類的資訊,獲取類的資訊首先要獲取類的類型別 a a1 new a class c a1.getclass 獲取方法 由名稱和引數列表來決定,getmethod獲取的是public方法,getdelcaredmetho...

方法反射的基本操作

1 如何獲取某個方法,方法的名稱和方法的引數列表才能唯一決定某個方法 2 方法反射的操作 method.invoke 物件,引數列表 public class methoddemo1 方法的反射操作,用m物件來進行方法呼叫,和a1.print呼叫的效果完全相同 方法如果沒有返回值,返回null,有返...

java反射 方法

取全部set方法 param t return public static final setget methods class t return methodset method知識 1.類方法 用static修飾的方法。由於類方法是屬於整個類的,所以類方法的方法體中不能有與類的物件有關的內容。即...