public class Toy {
private int i;
public Toy () {}
public Toy (int i) { this .i = i; }
public int getI () {
return i;
}
public int getValue (int val) {
return val;
}
}
public class ReflectTest {
public static void main (String[] args) throws Exception {
Class<Toy> toyClass = Toy.class;
Constructor<Toy> constructor = toyClass.getConstructor(int .class);
Toy toy = constructor.newInstance(1 );
Method method = toyClass.getMethod("getValue" , int .class);
System.out.println(method.invoke(toy, 10 ));
Field field = toyClass.getDeclaredField("i" );
field.setAccessible(true );
field.set(toy, 12 );
System.out.println(toy.getI());
}
}
Class<Toy> toyClass = Toy.class;
获取Toy
的class
,当然也可以使用Class.forName
获得,不过它获得需要处理一下。toyClass.getConstructor(int.class);
获取Toy
的带有一个int
型参数的构造器。Toy toy = constructor.newInstance(1);
使用上面获取的构造器实例化,参数为该构造器需要的参数。Method method = toyClass.getMethod("getValue", int.class);
获得Toy
的参数为一个int
型值的getValue
方法。method.invoke(toy, 10)
调用Toy
实例toy
的getValue
方法,参数为10
,必须和上面获取到的方法参数类型对应。Field field = toyClass.getDeclaredField("i");
获取Toy
类的i
域。field.setAccessible(true);
如果该域为private
,通过该方法设置能够被访问,不然会抛出异常。field.set(toy, 12);
设置Toy
实例toy
的i
域值为12
。