反射:通过配置文件运行类中的方法
实验代码
Student类
Student.java
package ReflectTest;
public class Student {
public void study(){
System.out.println("好好学习,天天向上");
}
}
配置文件:class.txt
可以通过改动className来改变要运行的类
通过改动methodName来改变要运行的方法这里类需要是public
className=ReflectTest.Student
methodName=study
主方法代码
ReflectTest1.java
package ReflectTest;
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 ReflectTest1 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
/*
反射练习:通过配置文件运行类中的方法
class.txt
class.Name=xxx
methodName=xxx
*/
//加载数据
Properties prop = new Properties();
FileReader fr = new FileReader("C:\\Users\\Linyz\\IdeaProjects\\First\\src\\class.txt");
prop.load(fr);
fr.close();
String className = prop.getProperty("className");
String methodName = prop.getProperty("methodName");
//创建Class对象
Class<?> c = Class.forName(className);
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//通过getMethod方法获取Student类的study成员方法
Method method = c.getMethod(methodName);
//通过invoke方法调用study方法
method.invoke(obj);
}
}
Properties类概述
1.是一个map体系的集合类。2.Properties可以保存到流中或者从流中加载。
作为集合的特有方法
1.Objec setProperty(String Key,String value):设置集合的键和值,调用底层Hashtable方法
2.String getProperty(String Key):指定键搜索值`该实验用到这个方法`
3.Set<String> stringPropertyNames():返回一个不可修改的键集,其中键是字符串
和IO流结合的方法
1.void load(Inputstream inStream):从输入`字节流`读取属性列表(键和元素对)
2.void load(Reader reader):从输入`字符流`读取属性列表(键和元素对)
3.void store(OutputStream out,String comments):将此属性列表写入Properties表中,适用于`字节流`使用的load
4.void store(Writer writer,String comments):将此属性列表写入Properties表中,适用于`字符流`使用的load
总结
Java基础学习小练习,欢迎讨论