利用反射加载配置文件,并动态创建对象和调用方法实战

利用反射加载配置文件,并动态创建对象和调用方法实战

步骤1:在src下创建prop.properties配置文件

className=com.itheima.myreflect1.Worker
methodName=work

步骤2:创建Worker和Teacher配置类

package com.itheima.myreflect1;
public class Worker {
    private String name;
    private int age;
    public Worker() { }
    public Worker(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name;}
    public void setName(String name) {this.name = name;}
    public int getAge() { return age;}
    public void setAge(int age) { this.age = age;}
    public void work(){
        System.out.println("工人在工作");
    }

    @Override
    public String toString() {
        return "Worker{" + "name='" + name + '\'' +", age=" + age + '}';
    }
}
package com.itheima.myreflect1;
public class Teacher {
    private String name;
    private int age;
    public Teacher() {}
    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {  return name;}
    public void setName(String name) {   this.name = name;}
    public int getAge() {   return age; }
    public void setAge(int age) {  this.age = age; }
    public void teach(){
        System.out.println("老师在上课");
    }
    @Override
    public String toString() {
        return "Teacher{" + "name='" + name + '\'' +  ", age=" + age + '}';
    } 
}

步骤3:利用反射加载配置文件,并动态创建对象和调用方法

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectDemo1 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,InstantiationException {
        //获取系统类加载器,加载prop.properties文件
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("prop.properties");
        //创建Properties集合
        Properties prop = new Properties();
        //将文件中的数据读取到集合当中
        prop.load(is);
        is.close();

        //--------下面的代码就是利用反射创建对象并调用方法---------------------

        //获取字节码文件对象
        Class clazz = Class.forName(prop.getProperty("className"));
        //获取构造器对象
        Constructor constructor = clazz.getConstructor();
        //利用构造器对象创建一个对象
        Object o = constructor.newInstance();
        //获取方法对象
        Method method = clazz.getMethod(prop.getProperty("methodName"));
        //运行方法
        method.invoke(o);
    }
}

你可能感兴趣的:(阶段二Java,java,反射)