[Java基础]反射练习之越过泛型检查,运行配置文件制定内容
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]反射练习之越过泛型检查,运行配置文件制定内容相关的知识,希望对你有一定的参考价值。
代码如下:
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.Student
methodName = 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.txt
className = xxx
methodName = xxx
*/
//加载数据
Properties prop = new Properties();
FileReader fr = new FileReader("D:\\\\javaTEST\\\\class.txt");
prop.load(fr);
fr.close();
/*
className = ReflectDemoPack.Student
methodName = 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);
}
}
以上是关于[Java基础]反射练习之越过泛型检查,运行配置文件制定内容的主要内容,如果未能解决你的问题,请参考以下文章