代码如下:
package ReflectTest01;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;public class ReflectTest01 {public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {ArrayList<Integer> array = new ArrayList<Integer>();Class<? extends ArrayList> c = array.getClass();Method m = c.getMethod("add", Object.class);m.invoke(array,"hello");m.invoke(array,"world");m.invoke(array,"java");System.out.println(array);}}
测试结果:
text文件:
className = ReflectDemoPack.StudentmethodName = study
代码如下:
package ReflectDemoPack;public class Teacher {public void teach(){System.out.println("用爱成就学员");}}
package ReflectDemoPack;public class Student {public void study(){System.out.println("好好学习,天天向上");}
}
package ReflectDemoPack;import java.io.FileNotFoundException;
import java.io.FileReader;
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 ReflectTest02 {public static void main(String[] args) throws IOException, NoSuchMethodException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
// Student s = new Student();
// s.study();// Teacher t = new Teacher();
// t.teach();/*class.txtclassName = xxxmethodName = xxx*///加载数据Properties prop = new Properties();FileReader fr = new FileReader("D:\\javaTEST\\class.txt");prop.load(fr);fr.close();/*className = ReflectDemoPack.StudentmethodName = study*/String className = prop.getProperty("className");String methodName = prop.getProperty("methodName");Class<?> c = Class.forName(className);Constructor<?> con = c.getConstructor();Object obj = con.newInstance();Method m = c.getMethod(methodName);m.invoke(obj);}
}