反射
- 运行过程中动态的修改一个类中的信息(针对class文件)。
- 动态: 代码在执行过程中可以改变自身的结构
package 反射;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
Person p1 = new Person();
Class<Person> cls = Person.class;
@Test
void Test1() throws Exception {
Class cls1 = Person.class;
Class cls2 = Class.forName("反射.Person");
Class cls3 = p1.getClass();
System.out.println(cls1==cls2&&cls2==cls3);
System.out.println(cls1);
}
@Test
void Test2() throws Exception {
Constructor<Person> con = cls.getDeclaredConstructor(int.class);
con.setAccessible(true);
Person p3 = con.newInstance(1);
System.out.println(p3.getAge());
}
@Test
void Test3() throws Exception {
Field[] fs = cls.getDeclaredFields();
for (Field f : fs) {
System.out.println(f);
}
Field age = cls.getDeclaredField("age");
age.setAccessible(true);
age.set(p1, 10);
System.out.println(age.get(p1));
}
@Test
void Test4() throws Exception {
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms) {
System.out.println(m);
}
Method show = cls.getDeclaredMethod("show");
show.setAccessible(true);
System.out.println(show.invoke(p1, null));
}
}
class Person{
private int age;
public String nation = "China";
public Person() {
}
int getAge() {
return age;
}
private Person(int age){
this.age = age;
}
private boolean show(){
System.out.printf("今年我%d岁了\n",this.age);
return true;
}
}