Java通过反射来加载配置文件调用对应的类

通过反射加载配置文件的方式加载类

  1. 创建配置文件(以properties结尾)
className=Entity.Student
methodName=sleep
  1. 创建本次实验的实体类Person
public class Person {
    private String name;
    private String age;
    public String a;
    public String b;
    protected String c;
    protected String d;

    public Person() {

    }
    public Person(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }

    public String getAge() {
        return age;
    }

    public Person setAge(String age) {
        this.age = age;
        return this;
    }

    public String getA() {
        return a;
    }

    public Person setA(String a) {
        this.a = a;
        return this;
    }

    public String getB() {
        return b;
    }

    public Person setB(String b) {
        this.b = b;
        return this;
    }

    public String getC() {
        return c;
    }

    public Person setC(String c) {
        this.c = c;
        return this;
    }

    public String getD() {
        return d;
    }

    public Person setD(String d) {
        this.d = d;
        return this;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }
    public void eat(){
        System.out.println("吃饭");
    }
    public void eat(String rou){
        System.out.println("吃"+rou);
    }

}

  1. 核心加载代码
public class ReflectCase {
    public static void main(String[] args)throws Exception {
        Properties properties = new Properties();
        ClassLoader classLoader = ReflectCase.class.getClassLoader();  //得到调用类加载器
        InputStream is = classLoader.getResourceAsStream("pro.properties");//获取配置文件字节流
        properties.load(is);//加载配置文件
        //获取配置文件中定义的数据
        String className=properties.getProperty("className");
        String methodName=properties.getProperty("methodName");
        //加载该类进内存
        Class<?> cls= Class.forName(className);//获取待加载类字节码文件
        Object obj = cls.newInstance();//默认构造方法
        Method method = cls.getMethod(methodName);
        method.invoke(obj);//执行指定方法
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进程盈赓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值