反射练习一文件录入-版本2-答案参考
链接: 反射练习一文件录入-版本2
---------
配置文件:
file_class_name=java.io.File
create_file_method=createNewFile
writer_class_name=java.io.Writer
file_writer_class_name=java.io.FileWriter
write_method=write
flush_method=flush
close_method=close
file_name=E:/a/data.txt
data_msg = "你好 JAVA! 我爱 JAVA"
JAVA代码:
package demofile;
import utils.FileUtils;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IOException,
InvocationTargetException, InstantiationException, IllegalAccessException {
//调用FileUtils工具类读取配置文件
Properties props = FileUtils.loadProps("file.properties");
//通过配置文件内数据反射读取对应class文件
Class<?> cls = Class.forName(props.getProperty("file_class_name"));
//反射调用createNewFile方法
Method newFile = cls.getDeclaredMethod(props.getProperty("create_file_method"));
Constructor<?> con = cls.getDeclaredConstructor(String.class);
Object o = con.newInstance(props.getProperty("file_name"));
newFile.invoke(o);
Class<?> cls1 = Class.forName(props.getProperty("writer_class_name"));
Class<?> cls2 = Class.forName(props.getProperty("file_writer_class_name"));
//反射创建文件对象
Object o1 = cls2.getDeclaredConstructor(String.class).newInstance(props.getProperty("file_name"));
//反射调用write方法
Method write = cls1.getDeclaredMethod(props.getProperty("write_method"), String.class);
write.invoke(o1,props.getProperty("data_msg"));
//反射调用flush方法
Method flush = cls1.getDeclaredMethod(props.getProperty("flush_method"));
flush.invoke(o1);
//反射调用close方法
Method close = cls1.getDeclaredMethod(props.getProperty("close_method"));
close.invoke(o1);
}
}
本文来自博客园,作者:xiaoyongdata(微信号:xiaoyongdata),转载请注明原文链接:https://www.cnblogs.com/xiaoyongdata/p/16407804.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!