黑马程序员技术交流社区
标题:
反射入门3-获得方法并调用
[打印本页]
作者:
游呤人
时间:
2015-7-16 01:41
标题:
反射入门3-获得方法并调用
Method 提供关于类或接口上单独某个方法(以及如何访问该方法)的信息。所反映的方法可能是类方法或实例方法(包括抽象方法)。
步骤和前面一样,先获得Class
方法有
Method getMethod(String name, Class<?>... parameterTypes)
返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
Method[] getMethods()
返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。
Method getDeclaredMethod(String name, Class<?>... parameterTypes)
返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。
Method[] getDeclaredMethods()
返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
public class MethdeDome {
public static void main(String[] args) throws Exception{
Class clazz=Class.forName("com.refect.Student");
Constructor con=clazz.getDeclaredConstructor();
con.setAccessible(true);
Object ob= con.newInstance();
System.out.println(ob);
/*Method[] me=clazz.getDeclaredMethods();
for (Method method : me) {
System.out.println(method);
}*/
System.out.println("---------------------><_____________________><-----------------------");
Method setAge =clazz.getDeclaredMethod("setAge", int.class);
System.out.println(setAge);
setAge.invoke(ob, 10);
System.out.println(ob);
Method hop=clazz.getDeclaredMethod("hop", null);
hop.setAccessible(true);
hop.invoke(ob, null);
}
}
复制代码
作者:
eayonh
时间:
2015-7-16 01:53
学习了……
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2