看了反射,记录一下,非常好用!
定义一个公共接口
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 block
e.printStackTrace();
}
}
}