(1)使用反射可以读取配置文件。简化代码
public class test {
public static void main(String[] args) throws Exception {
Properties pro = new Properties();
//File file = new File("prperties.txt");
//System.out.println(file.getAbsolutePath());
InputStream in = new FileInputStream("prperties.txt");
pro.load(in);
Set<String> set = pro.stringPropertyNames();
for(String str: set)
System.out.println(str);
String className = pro.getProperty("className");
String methodName = pro.getProperty("methodName");
System.out.println(methodName);
System.out.println(className);
Class c = Class.forName(className);
Constructor constructor = c.getConstructor();
Object obj = constructor.newInstance();
Method method = c.getDeclaredMethod(methodName);
method.setAccessible(true);
method.invoke(obj);
}
(2)越过泛型检查
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
ArrayList<Integer> array = new ArrayList<Integer>();
// 下面的代码不能越过泛型检查
// array.add("hello");
// 利用反射越过泛型检查
Class arrayClass = array.getClass();
Method method = arrayClass.getMethod("add", Object.class);
method.invoke(array, "hello");
Iterator iterator = array.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}