返射

编程入门 行业动态 更新时间:2024-10-08 03:27:54

返射

返射

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());

}


}

转载于:.html

更多推荐

返射

本文发布于:2024-02-14 08:46:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1762646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!