反射与注解

通过注解的方式与反射调用方法
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Test02> c = Test02.class;
        Anno anno = c.getAnnotation(Anno.class);//获取当前类指定的注解对象
        String className = anno.className();//获取指定的注解
        String methodName = anno.methodName();//获取指定的注解
        Class<?> c1 = Class.forName(className);//通过获取的注解获取目标类的字节码对象
        Constructor<?> cons = c1.getConstructor();//得到目标类的构造方法
        Object obj = cons.newInstance();//通过构造方法创建对象
        Method method = c1.getMethod(methodName);//通过字节码对象得到目标类中的方法
        method.invoke(obj);通过反射调用方法
    }
}

通过配置文件与反射调用方法

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, 					IllegalAccessException, InvocationTargetException, InstantiationException {
            Properties pro = new Properties();
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("run.properties");//
            pro.load(is);//加载配置文件,可以将Properties看做一个集合,将加载到的配置文件以键值对的形式放在Properties集合中
            String className = pro.getProperty("className");//通过键名获取值
            String methodName = pro.getProperty("methodName");//通过键名获取值
            Class<?> c = Class.forName(className);//通过得到的目标类的路径获取该类的字节码对象
            Constructor<?> con = c.getConstructor();//通过反射获取该类的构造方法对象
            Object obj = con.newInstance();//通过构造方法创建对象
            Method method = c.getMethod(methodName);//通过放射得到该类的方法
            method.invoke(obj);//通过反射调用方法
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值