给你一个小的实例代码:
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class test {
public static void main(String args[]) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
Foo foo = new Foo("这个一个Foo对象!");
Class clazz = foo.getClass();
Method m1 = clazz.getDeclaredMethod("outInfo");
Method m2 = clazz.getDeclaredMethod("setMsg", String.class);
Method m3 = clazz.getDeclaredMethod("getMsg");
m1.invoke(foo);
m2.invoke(foo, "重新设置msg信息!");
String msg = (String) m3.invoke(foo);
System.out.println(msg);
}
}
class Foo {
private String msg;
public Foo(String msg) {
this.msg = msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void outInfo() {
System.out.println("这是测试Java反射的测试类");
}
}
Class c=Class.forName("entity.Student");//获得对象的类加载器
Field[] f=c.getFields();//获得改对象的属性
for (int i = 0; i < f.length; i++) {
System.out.println(f[i].getName());
}
Student stu=(Student)c.newInstance();//反射出实例
Field f=c.getDeclaredField("name");//通过属性名称获得私有属性
f.setAccessible(true);//打开私有属性访问权限
f.set(stu, "zs");//通过类对象对对象属性赋值
System.out.println(stu.getName());
}
//获得构造
Constructor cons=c.getDeclaredConstructor(new Class []{String.class,int.class});
Method met=c.getMethod("setAge",new Class[]{Integer.TYPE});//获得方法
met.setAccessible(true);//打开访问权限
met.invoke(stu, 10);.//调用方法,传入对象,第二个参数是被调用方法传的参数,没有就写null