package day3;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionDemo2 {
@Test
public void testField() throws Exception {
Class c1= Person.class;
Person p1=(Person)c1.newInstance();
Field age = c1.getField("age");
age.set(p1,123);
System.out.println((int)age.get(p1));
Field name = c1.getDeclaredField("name");
name.setAccessible(true);
name.set(p1,"Tom");
System.out.println((String)name.get(p1));
}
@Test
public void testMethod() throws Exception {
Class c1= Person.class;
Person p1=(Person)c1.newInstance();
Method show = c1.getDeclaredMethod("showNation", String.class);
show.setAccessible(true);
System.out.println((String) show.invoke(p1,"China"));
Method showDetail = c1.getDeclaredMethod("showDetail");
showDetail.setAccessible(true);
showDetail.invoke(c1);
showDetail.invoke(null);
}
}
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 "姓名:"+ name + ",年龄:" + age;
}
public String show(){
return this.name+" , "+this.age;
}
private String showNation(String nation){
return "我来自"+nation;
}
private static void showDetail(){
System.out.println("谁是最可爱的人");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?