反射机制代码示例

  • 反射:即通过外部文件的配置,在不修改源码的条件下,控制程序。也符合设计模式的ocp原则(开闭原则:不修改源码,扩容功能)
  • 示例如下根据配置文件re.properties指定信息,创建Cat对象并调用hi方法
  • classfullpath=com.elf.Cat
  • method =hi
package com.elf.reflection.question;

import com.elf.Cat;

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;

/**
 * @author 45~
 * @version 1.0
 */
@SuppressWarnings({"all"})
public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath = properties.get("classfullpath").toString();
        String methodName = properties.get("method").toString();
        System.out.println("classfullpath=" + classfullpath);
        System.out.println("method=" + methodName);
        //创建对象,传统的方法行不通。就要使用反射机制
        // Cat cat = new com.elf.Cat();
        //3.使用反射机制解决
        //(1)加载类,返回Class类型的对象
        Class cls = Class.forName(classfullpath);//开头Class就是一个类,他的名字就叫Class
        //(2) 通过cls得到你加载的类com.elf.Cat的对象实例
        Object o = cls.newInstance();
        System.out.println("o的运行类型"+o.getClass());//得到它的运行类型
        //(3)通过cls得到加载的类com.elf.Cat的methodName的方法对象
        //即:在反射中,可以把方法视为对象(万物皆对象)
        Method method1 = cls.getMethod(methodName);
        //(4)通过method1调用方法:即通过方法对象来实现调用方法
        System.out.println("=============");
        method1.invoke(o);
    }
}

classfullpath=com.elf.Cat
//method=hi 修改的是配置文件
method=cry
package com.elf;

/**
 * @author 45~
 * @version 1.0
 */
public class Cat {
    private String name = "招财猫";

    public void hi() {//常用方法
        System.out.println("hi" + name);
    }

    public void cry() {//常用方法
        System.out.println("cry" + name);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值