反射相关的API
package com.atguigu.java;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionTest {
@Test
public void test1() {
Person p1 = new Person("Tom", 12);
p1.age = 10;
System.out.println(p1.toString());
p1.show();
}
@Test
public void test2() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
Class<Person> clazz = Person.class;
Constructor<Person> cons = clazz.getConstructor(String.class, int.class);
Object obj = cons.newInstance("Tom", 12);
Person p = (Person) obj;
System.out.println(p.toString());
Field age = clazz.getDeclaredField("age");
age.set(p, 10);
System.out.println(p.toString());
Method show = clazz.getDeclaredMethod("show");
show.invoke(p);
System.out.println("******************************************************");
Constructor<Person> cons1 = clazz.getDeclaredConstructor(String.class);
cons1.setAccessible(true);
Person p1 = (Person) cons1.newInstance("Jerry");
System.out.println(p1);
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(p1, "hahahahaha");
System.out.println(p1.toString());
Method showNation = clazz.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String nation = (String) showNation.invoke(p1,"中国");
System.out.println(nation);
}
}
package com.atguigu.java;
public 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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void show() {
System.out.println("你好,我是一个人");
}
private String showNation(String nation) {
System.out.println("我的国际是" + nation);
return nation;
}
}