运用反射读配置动态调用方法

来源:互联网 发布:社工库qq群数据库 编辑:程序博客网 时间:2024/06/06 03:46

看了反射,记录一下,非常好用!

定义一个公共接口

public interface IOffice {     public void run(String s);}

实现类

public class WordImpl implements IOffice { public void run(String s){System.out.println("Word"+s);}}

public class ExcelImpl implements IOffice{public  void run(String s){System.out.println("Excel"+s);}}

配置文件 config.properties

method=run

一个操作配置的工具类

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.Properties;public class PropertiesUtil {private String configPath = null;private Properties props = null;public PropertiesUtil() throws IOException {InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties");props = new Properties();props.load(in);in.close();}public String readValue(String key) throws IOException {return props.getProperty(key);}public Map<String, String> readAllProperties() throws FileNotFoundException, IOException {Map<String, String> map = new HashMap<String, String>();Enumeration en = props.propertyNames();while (en.hasMoreElements()) {String key = (String) en.nextElement();String Property = props.getProperty(key);map.put(key, Property);}return map;}public void setValue(String key, String value) throws IOException {Properties prop = new Properties();InputStream fis = new FileInputStream(this.configPath);prop.load(fis);OutputStream fos = new FileOutputStream(this.configPath);prop.setProperty(key, value);prop.store(fos, "last update");fis.close();fos.close();}}

测试类

import java.lang.reflect.Method;public class Demo {public static void main(String[] args) {try {Class c = Class.forName(args[0]);IOffice iof = (IOffice) c.newInstance();Method m = iof.getClass().getMethod(new PropertiesUtil().readValue("method"), String.class);m.invoke(iof, "动态调用");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


本例试验了动态调用实现类实例化对象和通过反射从参数中调用方法,运行时输入参数WordImpl或ExcelImpl,其实也完全可以以配置文件的参数传入。

0 0
原创粉丝点击