[Java基础]反射练习之越过泛型检查,运行配置文件制定内容
生活随笔
收集整理的這篇文章主要介紹了
[Java基础]反射练习之越过泛型检查,运行配置文件制定内容
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼如下:
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);}}測(cè)試結(jié)果:
text文件:
className = ReflectDemoPack.StudentmethodName = study代碼如下:
package ReflectDemoPack;public class Teacher {public void teach(){System.out.println("用愛成就學(xué)員");}} package ReflectDemoPack;public class Student {public void study(){System.out.println("好好學(xué)習(xí),天天向上");} } 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*///加載數(shù)據(jù)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);} }總結(jié)
以上是生活随笔為你收集整理的[Java基础]反射练习之越过泛型检查,运行配置文件制定内容的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生酮减肥好不好
- 下一篇: [Java基础]模块化概述