调用运行时类的指定结构:属性、方法、构造器

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();
        //get,获取运行时类及其父类的public的属性
        Field age = c1.getField("age");
        age.set(p1,123);
        System.out.println((int)age.get(p1));

        //getDeclared,获取运行时类任意权限的属性
        Field name = c1.getDeclaredField("name");
        //把非public的属性设置为可访问
        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("谁是最可爱的人");
    }
}
posted @   fighterk  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示