Java 方法反射的基本操作

来源:互联网 发布:高仿淘宝模板 编辑:程序博客网 时间:2024/05/16 19:14
方法的反射: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[]{int.class,int.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{void printInfo(String s1, String s2){System.out.println(s1 + s2);}}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[]{String.class,String.class});Object o = m.invoke(a, "Hello ", "World!");//Here, o = null//You can also write like:Object o = m.invoke(a, new Object[]{"Hello ","World!"});//The above code just like:a.printInfo("Hello ","World!");

0 0
原创粉丝点击