反射练习一文件录入-版本2
链接:
反射练习一文件录入-版本1
版本1的答案和新的要求:
package demofile; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** File file = new File("d:/demo/f1.txt"); file.createNewFile(); ... 想法:不修改main方法中的代码,但是想改变程序的行为。 方案1:用注解....确实在此不十分合适。 方案2:用配置文件-示意。 file.properties: 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 content=content1,content2,content3 content1=你好 JAVA1 content2=你好 JAVA2 content3=你好 JAVA3 */ public class Demo { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException { //1.定义类名 String clsName = "java.io.File"; String msg = "你好 JAVA"; String path = "E:/a/data.txt"; //2.获取Class对象cls Class<?> cls = Class.forName(clsName); //3.获取指定方法-createNewFile Method newFile = cls.getDeclaredMethod("createNewFile"); //4.创建一个File对象 Constructor<?> con = cls.getDeclaredConstructor(String.class); Object o = con.newInstance(path); //5.通过invoke调用方法 newFile.invoke(o); //下同... String clsName1 = "java.io.Writer"; Class<?> cls1 = Class.forName(clsName1); String clsName2 = "java.io.FileWriter"; Class<?> cls2 = Class.forName(clsName2); Object o1 = cls2.getDeclaredConstructor(String.class).newInstance(path); Method write = cls1.getDeclaredMethod("write", String.class); write.invoke(o1,msg); Method flush = cls1.getDeclaredMethod("flush"); flush.invoke(o1); Method close = cls1.getDeclaredMethod("close"); close.invoke(o1); } }
本文来自博客园,作者:xiaoyongdata(微信号:xiaoyongdata),转载请注明原文链接:https://www.cnblogs.com/xiaoyongdata/p/16399143.html