生活随笔
收集整理的這篇文章主要介紹了
反射获取成员方法并使用【应用】
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Class類獲取成員方法對(duì)象的方法
-
方法分類
方法名說(shuō)明
| Method[] getMethods() | 返回所有公共成員方法對(duì)象的數(shù)組,包括繼承的 |
| Method[] getDeclaredMethods() | 返回所有成員方法對(duì)象的數(shù)組,不包括繼承的 |
| Method getMethod(String name, Class<?>... parameterTypes) | 返回單個(gè)公共成員方法對(duì)象 |
| Method getDeclaredMethod(String name, Class<?>... parameterTypes) | 返回單個(gè)成員方法對(duì)象 |
-
示例代碼
public class ReflectDemo01 {public static void main(String[] args) throws Exception {//獲取Class對(duì)象Class<?> c = Class.forName("com.leon_02.Student");//Method[] getMethods() 返回一個(gè)包含 方法對(duì)象的數(shù)組, 方法對(duì)象反映由該 Class對(duì)象表示的類或接口的所有公共方法,包括由類或接口聲明的對(duì)象以及從超類和超級(jí)接口繼承的類//Method[] getDeclaredMethods() 返回一個(gè)包含 方法對(duì)象的數(shù)組, 方法對(duì)象反映由 Class對(duì)象表示的類或接口的所有聲明方法,包括public,protected,default(package)訪問和私有方法,但不包括繼承方法
// Method[] methods = c.getMethods();Method[] methods = c.getDeclaredMethods();for(Method method : methods) {System.out.println(method);}System.out.println("--------");//Method getMethod(String name, Class<?>... parameterTypes) 返回一個(gè) 方法對(duì)象,該對(duì)象反映由該 Class對(duì)象表示的類或接口的指定公共成員方法//Method getDeclaredMethod(String name, Class<?>... parameterTypes) 返回一個(gè) 方法對(duì)象,它反映此表示的類或接口的指定聲明的方法 Class對(duì)象//public void method1()Method m = c.getMethod("method1");//獲取無(wú)參構(gòu)造方法創(chuàng)建對(duì)象Constructor<?> con = c.getConstructor();Object obj = con.newInstance();// obj.m();//在類或接口上提供有關(guān)單一方法的信息和訪問權(quán)限//Object invoke(Object obj, Object... args) 在具有指定參數(shù)的指定對(duì)象上調(diào)用此 方法對(duì)象表示的基礎(chǔ)方法//Object:返回值類型//obj:調(diào)用方法的對(duì)象//args:方法需要的參數(shù)m.invoke(obj);// Student s = new Student();
// s.method1();}
}
Method類用于執(zhí)行方法的方法
方法名說(shuō)明
| Objectinvoke(Object obj,Object... args) | 調(diào)用obj對(duì)象的成員方法,參數(shù)是args,返回值是Object類型 |
反射獲取成員方法并使用練習(xí)【應(yīng)用】
-
案例需求
-
代碼實(shí)現(xiàn)
-
學(xué)生類:參見上方學(xué)生類
-
測(cè)試類
public class ReflectDemo02 {public static void main(String[] args) throws Exception {//獲取Class對(duì)象Class<?> c = Class.forName("com.leon_02.Student");//Student s = new Student();Constructor<?> con = c.getConstructor();Object obj = con.newInstance();//s.method1();Method m1 = c.getMethod("method1");m1.invoke(obj);//s.method2("林青霞");Method m2 = c.getMethod("method2", String.class);m2.invoke(obj,"林青霞");// String ss = s.method3("林青霞",30);
// System.out.println(ss);Method m3 = c.getMethod("method3", String.class, int.class);Object o = m3.invoke(obj, "林青霞", 30);System.out.println(o);//s.function();
// Method m4 = c.getMethod("function"); //NoSuchMethodException: com.itheima_02.Student.function()Method m4 = c.getDeclaredMethod("function");m4.setAccessible(true);m4.invoke(obj);}
}
?
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生
總結(jié)
以上是生活随笔為你收集整理的反射获取成员方法并使用【应用】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。