1 已知一个类,定义如下:
public class DemoClass {
public void run() {
System.out.println(“welcome to Beijing!”);
}
}
(1) 写一个Properties格式的配置文件,配置类的完整名称。
(2) 写一个程序,读取这个Properties配置文件,
获得类的完整名称并加载这个类,
用反射的方式运行run方法。
首先创建一个.properties文件
class DemoClass {
public void run() {
System.out.println("welcome to Beijing!");
}
}
public class Demo1 {
public static void main(String[] args) throws Exception, NoSuchMethodException, SecurityException {
//1.FileInputStream读取.Properties文件
FileInputStream fis = new FileInputStream("aa.properties");
//2.新建一个Properties实例
Properties pp = new Properties();
//3.从输入字节流中读取属性列表(键和元素对)
pp.load(fis);
//4.在此属性列表中搜索具有指定键的属性
String str = pp.getProperty("className");
//5.通过Class类的静态方法,获取Class对象
Class clazz = Class.forName(str);
//6.通过该构造方法创建一个该类的对象
Object obj = clazz.newInstance();
//7.获取权限为public的指定方法
Method me = clazz.getMethod("run", null);
//8.利用指定参数args执行指定对象obj中的该方法,返回值为Object型
me.invoke(obj, null);
}
}