反射配置文件

通过配置文件利用反射调用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);
        
    
        
    }

}

运行结果

posted @ 2019-07-04 19:51  勤奋的园  阅读(253)  评论(0编辑  收藏  举报