使用反射的第一步需要获得Class对象。
1.1 Class对象的获得
获得Class的三种方法:
1.1.1 Class.forName();
Class<?> classtype = Class.forName("java.lang.Object");
Method[] methods=classtype.getDeclaredMethods();
for(Methodm:methods){
System.out.println(m);
}
1.1.2 类名.class
Class<?> classtype=InvokeTester.class;
Object inv =classtype.newInstance(); //生成一个新实例
System.out.println(inv instanceof InvokeTester);
Method addMethod = classtype.getMethod("add", new Class[]{int.class,int.class});
Object result = addMethod.invoke(inv, new Object[]{1,2});
System.out.println(result);
System.out.println("----------------");
Method echoMethod = classtype.getMethod("echo", new Class[]{String.class});
Object result2 =echoMethod.invoke(inv, new Object[]{"HLOOEE"});
1.1.3 对象的.getClass()
public class ReflectTester {
public Object copy(Object object)throws Exception{
Class<?>classType = object.getClass();
// Constructor cons=classType.getConstructor(new Class[]{});
// Object obj = cons.newInstance(new Object[]{});
// 以上两行等价于:(如果构造一个对象需要参数,该方法无法完成。
// Object obj2 = classType.newInstance();
Constructor<?>cons=classType.getConstructor(newClass[]{String.class,int.class});
Objectobj = cons.newInstance(new Object[]{"Hello",3});
System.out.println(obj);
return obj;
}
public staticvoid main(String[] args) throws Exception {
ReflectTesterref = new ReflectTester();
Customercust =(Customer) ref.copy(newCustomer("ABC",45));
//cust.getName();
System.out.println(cust.getName());
//System.out.println(ref);
}
}
1.2 调用private方法或变量
package com.test.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestPrivate {
public staticvoid main(String[] args) throws Exception {
Cnewccc = new C();
Class<?>classtype = newccc.getClass();
Methodmethod = classtype.getDeclaredMethod("print",
new Class[] { String.class });
method.setAccessible(true);// 强制取消Access的访问权限检查,否则Error:java.lang.IllegalAccessException
method.invoke(newccc,new Object[] { "MMMMMM" });
Fieldfield = classtype.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.get(newccc));
field.set(newccc,"GOOD");
System.out.println(field.get(newccc));
}
}
class C {
private String name="Zhangsan";
private voidprint(String msg) {
System.out.println("hello"+ msg);
}
}
1.3 对象的生产方法
classtype.newInstance();//只能生产不带参数的构造函数
newCustomer()