反射配置文件

通过配置文件利用反射调用People类中的私有方法

配置文件properties.txt内容:

ClassName=com.zy.demo2.People
MethodName=method

package com.zy.demo2;

public class People {
    private void method(){
        System.out.println("我是method");
    }

}
package com.zy.demo2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;

public class Test {

    public static void main(String[] args) throws Exception {

        
        
        File file = new File("src/com/zy/demo2/properties.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        Properties properties = new Properties();
        properties.load(fileInputStream);//从输入字节流读取属性列表(键和元素对)。 
        
        Enumeration propertyNames = properties.propertyNames();//返回此属性列表中所有键的枚举
//        System.out.println(propertyNames.nextElement());//输出ClassName
        
        ArrayList<String> list = new ArrayList();
        
        while(propertyNames.hasMoreElements()){
            list.add(propertyNames.nextElement().toString());
        }
        for (String str : list) {
            System.out.println(str);
        }    
        
        System.out.println(properties.getProperty(list.get(0)));//com.zy.demo2.People
        System.out.println(properties.getProperty(list.get(1)));//method    
        System.out.println("---------------------------------------------");
        //获取class对象
        Class forName = Class.forName(properties.getProperty(list.get(0)));
        //获取构造对象
        Constructor declaredConstructor = forName.getDeclaredConstructor();
        //创建实例对象
        Object uu = declaredConstructor.newInstance();
        //获取方法
        Method declaredMethod = forName.getDeclaredMethod(properties.getProperty(list.get(1)));
        //开启暴力访问
        declaredMethod.setAccessible(true);
        //调用方法
        declaredMethod.invoke(uu);
        
    
        
    }

}

运行结果

转载于:https://www.cnblogs.com/qfdy123/p/11134569.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值