package test;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
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);
p1.show();
}
@Test
public void test2() throws Exception {
Class calzz = Person.class;
Constructor cons = calzz.getConstructor(String.class, int.class);
Object obj = cons.newInstance("Tom", 12);
Person p = (Person) obj;
System.out.println(p);
Field age = calzz.getDeclaredField("age");
age.set(p, 10);
System.out.println(p);
Method show = calzz.getDeclaredMethod("show");
show.invoke(p);
Constructor cons1 = calzz.getDeclaredConstructor(String.class);
cons1.setAccessible(true);
Person p1 = (Person) cons1.newInstance("Jerry");
System.out.println(p1);
Method showNation = calzz.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String nation = (String) showNation.invoke(p1, "中国");
System.out.println(nation);
}
}
Person{name='Tom', age=12}
Person{name='Tom', age=10}
hello
Person{name='Jerry', age=0}
中国
中国
进程已结束,退出代码0
package test;
public class Person {
private String name;
public int age;
private Person(String name) {
this.name = name;
}
public Person() {
}
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;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void show() {
System.out.println("hello");
}
private String showNation(String nation) {
System.out.println(nation);
return nation;
}
}
@Test
public void test3() throws ClassNotFoundException {
Class clazz1 = Person.class;
System.out.println(clazz1);
Person p1 = new Person();
Class clazz2 = p1.getClass();
System.out.println(clazz2);
Class clazz3 = Class.forName("test.Person");
System.out.println(clazz3);
System.out.println(clazz1 == clazz2);
System.out.println(clazz1 == clazz3);
ClassLoader classLoader = ReflectionTest.class.getClassLoader();
Class clazz4 = classLoader.loadClass("test.Person");
System.out.println(clazz4);
System.out.println(clazz1 == clazz4);
}
}
class test.Person
class test.Person
class test.Person
true
true
class test.Person
true
进程已结束,退出代码0