调用运行时类中指定的结构
总结于尚硅谷学习视频
所用Person类
package com.day0326_1;
import com.day0324_1.Person;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionTest {
@Test
public void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
Class clazz= Person.class;
Person p = (Person) clazz.newInstance();
Field id = clazz.getField("id");
id.set(p,1001);
int pId= (int) id.get(p);
System.out.println(pId);
}
@Test
public void test2() throws Exception {
Class clazz= Person.class;
Person p = (Person) clazz.newInstance();
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(p,"Tom");
System.out.println(name.get(p));
}
@Test
public void testMethod() throws Exception {
Class clazz= Person.class;
Person p = (Person) clazz.newInstance();
Method show = clazz.getDeclaredMethod("show", String.class);
show.setAccessible(true);
Object returnValue=show.invoke(p,"CHN");
System.out.println(returnValue);
System.out.println("*********如何调用静态方法*********");
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
Object returnVal=showDesc.invoke(Person.class);
System.out.println(returnVal);
}
@Test
public void testConstructor() throws Exception {
Class clazz =Person.class;
Constructor constructor = clazz.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
Person per = (Person) constructor.newInstance("Tom");
System.out.println(per);
}
}