反射

一、获取Class对象的三种方式:

方式: 通过Object类中的getObject()方法

 

Person p = new Person();
Class c = p.getClass();

 

方式二:通过 类名.class

 

Class c2 = Person.class;

 

方式三通过Class类中的方法(将类名作为字符串传递给Class类中的静态方法forName即可);

 

Class c3 = Class.forName("Person");

 

l 注意:第三种和前两种的区别

前两种你必须明确Person类型.

后面是指定这种类型的字符串就行.这种扩展更强.我不需要知道你的类.我只提供字符串,按照配置文件加载就可以了;

下面为啥添加123 时候会报错 原因:在于有了泛型约束  要想把int类型存进去 需要泛型擦除

 

public class Demo01 {

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        List<String> arr=new ArrayList<String>();
        arr.add("abc");
        arr.add(123);//泛型约束所以报错
        //这时候就用到泛型擦除
        //获取Arraylist 的class对象
        Class c=arr.getClass();
        //获取add方法对象
        Method m=c.getMethod("add", Object.class);
        //执行方法
        m.invoke(arr, 123);
        for(Object o:arr){
            System.out.println(o);
        }
    }
}

 

 

配置反射文件(重点):

分别创建3个构造方法:

public class Student {
    public void study(){
        System.out.println("学生学习");
    }
}

public class Work {
    public void work() {
        System.out.println("工人工作");
    }
}

public class Cooker {
    public void cook(){
        System.out.println("厨师炒菜");
    }
}

配置文件:

 

className=com.oracle.demo02.Student
methodName=study
#className=com.oracle.demo02.Worker
#methodName=work
#className=com.oracle.demo02.Cooker
#methodName=cook

 

public class Demo02 {

    public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, SecurityException, ClassNotFoundException {
        //创建properties集合
        Properties pro=new Properties();
        //明确数据源
        FileInputStream fis=new FileInputStream("src/com/oracle/demo02/config.properties");
        //将Properties文件中的数据读取到Properties中
        pro.load(fis);
        //获取完成包名+类名
        String className=pro.getProperty("className");
        //获取方法名
        String methodName=pro.getProperty("methodName");
        //获取class字节码文件对象
        Class c=Class.forName(className);
        //获取方法对象
        Method m=c.getMethod(methodName);
        //快速创建对象
        Object obj = c.newInstance();
        //执行方法
        m.invoke(obj);
    }
}

 这样想调用哪个时候只改动配置文件就可以了;

 

配置文件修改后:

#className=com.oracle.demo02.Student
#methodName=study
#className=com.oracle.demo02.Worker
#methodName=work
className=com.oracle.demo02.Cooker
methodName=cook

运行结果如下:

 

posted @ 2020-04-28 17:09  丿狂奔的蜗牛  阅读(81)  评论(0编辑  收藏  举报