反射思想由来已久,由于一直对java中反射的用法一直不太熟悉,特地找了一些资料学习了 一下,现在通过以下一些实例,对java中反射机制的一些用法做一些介绍:
获得实例对象的一个field,method,constructor
下面是一个简单的例子:
package reflection; import java.lang.reflect.Field; public class GetFieldSimple { public int height; private int width; public GetFieldSimple(int height, int width) { super(); this.height = height; this.width = width; } static void printHeight(GetFieldSimple gfs){ Field heigthField; Method method; Constructor cons; Integer height; Class c =gfs.getClass(); //获得运行时对象 //省略了try catch的代码 heigthField=c.getField("height"); //获得指定的字段封装为对象 height = heigthField.getInt(gfs); //从对象中取出字段值 System.out.println(height); heigthField=c.getDeclaredField("width");//width是private型 height = heigthField.getInt(gfs); System.out.println(height);
method=c.getMethod("printMethodName1"); System.out.println("method name"+method.getName()); method=c.getDeclaredMethod("printMethodName2");//printMethodName2 //是private型 System.out.println("method name"+method.getName());
cons=c.getConstructor(new Class[] {int.class,int.class}); System.out.println("cons "+cons.getName() +" "+cons.getTypeParameters()); } public static void main(String[] args) { GetFieldSimple gg = new GetFieldSimple(100, 200); printHeight(gg); } } |
运行后会报java.lang.NoSuchFieldException: width这个错误,这是因为width是一个private类型。
c.getField(“***”)这个方法可以返回c所表示的类或接口的所有的公共字段。
c.getDeclaredField("xxxx");返回已声明的field(包括private类型)。
Method中的getMethod() 获得public方法和getDelcaredMethod()可以获得所有。
static字段可以直接从类中取而不需要从对象中取等
更详细的用法,可以去多看看API。这个只是最简单的一个例子。