JAVA-反射机制-2023-03-18

反射机制,反过来,通过修改配置文件达到更新,拓展程序的目的,而不需要修改代码

传统方法:对象.方法() 反射机制:方法.invoke(对象)

实体类及方法

package com.feijian;

public class Cat {
    public String name="招财猫: ";
    public void hi(){
        System.out.println(name+" hi hi hi");
    }
    public void cry(){
        System.out.println(name+"喵 喵 喵");
    }
}

2.配置文件 re.properties 在resources目录下

classfulpath=com.feijian.Cat
method1=hi
method2=cry

3、测试

package com.feijian;

import com.sun.corba.se.impl.ior.OldJIDLObjectKeyTemplate;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //1.传统方法 new 一个对象,再调用方法
        //Cat cat = new Cat();
        //cat.hi();

        //2.通过文件流读入re.properties
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\main\\resources\\re.properties"));
        String classfulpath = properties.get("classfulpath").toString();
        String methodName1 = properties.get("method1").toString();
        String methodName2 = properties.get("method2").toString();
        System.out.println("classfulpath: "+classfulpath);
        System.out.println("method1: "+methodName1);
        System.out.println("method2: "+methodName2);

        //3.创建对象,使用反射机制
        //(1) 返回Class类型的对象 Class就是一个类,名字就叫做class
        Class cls = Class.forName(classfulpath);
        //(2)通过cls 得到你加载的类 com.feijian.Cat的对象
        //Object o =  cls.newInstance();
        //System.out.println(o.getClass());
        Cat o = (Cat) cls.newInstance();
        //(3)通过cls得到你加载的类 com.feijian.Cat 的methodName"hi" 的方法对象
        //即:在反射中,可以把方法也视为对象(万物皆对象)
        Method method1 = cls.getMethod(methodName1);
        Method method2 = cls.getMethod(methodName2);
        //(4)通过method来调用方法,即通过方法对象来实现调用方法
        method1.invoke(o);  //传统方法:对象.方法() 反射机制:方法.invoke(对象)
        method2.invoke(o);
    }
}
posted @ 2023-03-18 13:45  Rui2022  阅读(13)  评论(0编辑  收藏  举报