(Java)反射与文档注释

 

 

package com.reflect.test;

/**
 * @author Alina
 * @date 2022年02月01日 6:09 下午
 */
public class Demo1 {
    public void method(){
        System.out.println("Demo1...method");
    }
}
package com.reflect.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE}) //作用于类
@Retention(RetentionPolicy.RUNTIME)

public @interface pro {
    String className();
    String methodName();
}
package com.reflect.test;

import java.lang.reflect.Method;

/**
 * @author Alina
 * @date 2022年02月01日 6:21 下午
 */
@pro(className = "com.reflect.test.Demo1",methodName = "method")
public class ReflectTest {
    public static void main(String[] args) throws Exception{
        //1.解析注解
        //获取该类的字节码文件对象
        Class reflectTestClass = ReflectTest.class;
        //获取字节码对象的注解文件
        pro an = (pro) reflectTestClass.getAnnotation(pro.class);
        //调用注解对象中的方法
        String className = an.className();
        String methodName = an.methodName();
        //加载该类到内存
        Class cls = Class.forName(className);
        //创建对象
        Object obj = cls.newInstance();
        //获取对象方法
        Method method = cls.getMethod(methodName);
        //执行方法
        method.invoke(obj);









    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值