注解的基本使用方法

使用注解来实现前面的博客文章https://blog.csdn.net/weixin_42265250/article/details/99770810),前面使用的是采用配置配置文件来实现功能

1.编写自定义的注解:

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 MyAnno {
    String className();
    String methodName();
}

2.定义一个简单的实例类:

public class Person1 {
    public void show(){
        System.out.println("person1...show..");
    }
}

3.编写主类运行类:

import java.lang.reflect.Method;

@MyAnno(className = "pri.xlf.resouce.Person1",methodName = "show")
public class MyMain {
    public static void main(String[] args) throws Exception {
        //获取字节码文件对象
        Class<MyMain> cls = MyMain.class;
        //获取MyMain上面的注解对象
        //在内存中生成一个该注解接口的子类实现对象
        MyAnno anno = cls.getAnnotation(MyAnno.class);
        //通过 对象.方法名 进行获取值
        String className = anno.className();
        String methodName = anno.methodName();
        //System.out.println("className:"+className+"  methodName:"+methodName);
        //获取指定名称的类的字节码文件
        Class classname = Class.forName(className);
        //获取该类的对象
        Object obj = classname.newInstance();
        //获取指定的方法对象
        Method method = classname.getMethod(methodName);
        //调用方法
        method.invoke(obj);
    }
}

4.运行结果:

5.总结:

       之前使用 MyAnno anno = cls.getAnnotation(MyAnno.class);时获得的anno为null,是因为在编写注解的时候没有写上元注解@Retention(RetentionPolicy.RUNTIME)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值