package day3;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//调用运行时类的指定结构:属性、方法、构造器
public class ReflectionDemo2 {
@Test
public void testField() throws Exception {
Class c1= Person.class;
Person p1=(Person)c1.newInstance();
//get,获取运行时类及其父类的public的属性
Field age = c1.getField("age");
age.set(p1,123);
System.out.println((int)age.get(p1));
//getDeclared,获取运行时类任意权限的属性
Field name = c1.getDeclaredField("name");
//把非public的属性设置为可访问
name.setAccessible(true);
name.set(p1,"Tom");
System.out.println((String)name.get(p1));
}
@Test
public void testMethod() throws Exception {
Class c1= Person.class;
Person p1=(Person)c1.newInstance();
//通过方法名和形参列表,获取方法
Method show = c1.getDeclaredMethod("showNation", String.class);
show.setAccessible(true);
System.out.println((String) show.invoke(p1,"China"));
//调用静态方法
Method showDetail = c1.getDeclaredMethod("showDetail");
showDetail.setAccessible(true);
//调用者为运行时类
showDetail.invoke(c1);
showDetail.invoke(null);
}
}
class Person {
private String name;
public int age;
public Person(){
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "姓名:"+ name + ",年龄:" + age;
}
public String show(){
return this.name+" , "+this.age;
}
private String showNation(String nation){
return "我来自"+nation;
}
private static void showDetail(){
System.out.println("谁是最可爱的人");
}
}
标签:调用,name,Person,age,String,c1,时类,public,属性 From: https://www.cnblogs.com/fighterk/p/16939252.html