反射

public class Test001 {

@Test
public void test1() throws Exception {
getObjectClass();
getObjectStaticClass();
getForNameClass();
getMethodFromClass();
}

/**
* 1获取对象字节码
*
* Object中的getClass
*/
public void getObjectClass() {
Person p = new Person();
Class cp = p.getClass();
System.out.println(cp);
}

/**
* 2、获取对象字节码
*
* 静态方法.class
*/
public void getObjectStaticClass() {
Class cp = Person.class;
System.out.println(cp);
}

/**
* 3、获取对象字节码
* java.lang中的
* forName
*/
public void getForNameClass() throws Exception {
/**
* 空参
*/
String className="vo.Person";
Class cp=Class.forName(className);



Object obj = cp.newInstance();
if(obj instanceof Person){
System.out.println("obj"+obj);
}
System.out.println(cp);
/**
* 指定参数
*/

Constructor constructor= cp.getConstructor(String.class,int.class,Date.class);

Object obj1 = constructor.newInstance("丘小燕",123,new Date());

Field field = Class.forName(className).getDeclaredField("name");

/**
* 对私有字段取消返回检查
*/
field.setAccessible(true);

field.set(obj1,"丘大燕");

System.out.println(field.get(obj1));


}


public void getMethodFromClass() throws Exception {
String className="vo.Person";
Class clazz = Class.forName(className);
/**
* 取所有公有的方法
*/
// Method[] methods = clazz.getMethods();

/**
* 取所有的方法
*/
Method[] methods = clazz.getDeclaredMethods();

Stream.of(methods).forEach((e)->{
System.out.println(e);
});


Method method = clazz.getDeclaredMethod("show",String.class,int.class,Date.class);
method.setAccessible(true);
method.invoke(clazz.newInstance(),"丘燕燕",111,new Date());

}


}
posted on 2018-09-25 15:42  Legend_yan  阅读(147)  评论(0编辑  收藏  举报