反射练习一文件录入-版本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);
    }
}

 

 

 

 

posted @ 2022-06-24 10:13  xiaoyongdata  阅读(33)  评论(1编辑  收藏  举报