建立一个Person类便于测试
public class Person {
private String name;
public int age;
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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
private Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void show(){
System.out.println("我是chinese");
}
private void showMaker(){
System.out.println("我是sb");
}
}
反射基础的测试
@Test
public void test() throws Exception {
Class<Person> clazz = Person.class;
Constructor<Person> con = clazz.getConstructor(String.class, int.class);
Person tom = con.newInstance("Tom", 10);
//共有属性
Field field = clazz.getDeclaredField("age");
field.set(tom,12);
//私有属性
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(tom,"Jack");
//共有方法
Method show = clazz.getDeclaredMethod("show");
show.invoke(tom);
//私有方法
Method showMaker = clazz.getDeclaredMethod("showMaker");
showMaker.setAccessible(true);
showMaker.invoke(tom);