• 反射配置文件


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

    运行结果

  • 相关阅读:
    构建乘积数组
    数组中重复的数字
    把字符串转换成整数
    不用加减乘除做加法
    求1+2+3+...+n
    孩子们的游戏(圆圈中最后剩下的数)
    翻转单词顺序列
    扑克牌顺子
    左旋转字符串
    ES6必知必会 —— Module
  • 原文地址:https://www.cnblogs.com/qfdy123/p/11134569.html
Copyright © 2020-2023  润新知