java反射案例通过读取配置文件调用类方法

复制代码
package Reflects;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.stream.Stream;

public class ReflectDemo2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        System.out.println("=====练习:通过配置文件进行类操作=====");
        Properties p = new Properties();
//        p.setProperty("className","Reflects.Student");
//        p.setProperty("classMethod","study");
        p.setProperty("className","Reflects.Teacher");
        p.setProperty("classMethod","say");
        FileWriter fileWriter = new FileWriter("./config.txt");
        p.store(fileWriter,null);
        fileWriter.close();
        //读区
        FileReader fr = new FileReader("./config.txt");
        p.load(fr);
        fr.close();
        String className = p.getProperty("className");
        String classMethod = p.getProperty("classMethod");
        Class<?> aClass = Class.forName(className);  //获取类文件对象
        Constructor<?> constructor = aClass.getConstructor();//构造方法
        Object o = constructor.newInstance();//创建对象
        Method method = aClass.getMethod(classMethod);
        method.invoke(o);

    }
}
复制代码

 

posted @   phpwyl  阅读(171)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2018-04-28 php邮箱发送
点击右上角即可分享
微信分享提示