reflect与Properties的简单使用

    xiaoxiao2025-01-10  7

    配置配件如下

    然后运行程序

    package com.reflexAndProperties; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Properties; public class ReflexAndPropertiesTest { public static void main(String[] args) throws Exception { File file = new File("freshbin/reflex.properties"); Properties pro = new Properties(); pro.load(new FileInputStream(file)); String className = pro.getProperty("ClassName"); String name = pro.getProperty("name"); String cardId = pro.getProperty("cardId"); // System.out.println(className + "---" + name + "-------" + cardId); //获得字节码对象 Class c = Class.forName(className); //获得构造方法 Constructor con = c.getConstructor(); //创建一个实例 Object obj = con.newInstance(); System.out.println(obj); //得得setName方法 Method m1 = c.getMethod("setName", String.class); m1.invoke(obj, name); // System.out.println(m1); //得得setCardId方法 Method m2 = c.getMethod("setCardId", int.class); m2.invoke(obj, Integer.parseInt(cardId)); System.out.println(obj); //修改配置文件 pro.setProperty("name", "tyb"); pro.setProperty("cardId", "23"); //保存配置文件 pro.store(new FileOutputStream(file), ""); } }

    结果如下

    配置文件保存成功,如下

    转载请注明原文地址: https://ju.6miu.com/read-1295344.html
    最新回复(0)