注解简单笔记

注解

基本注解
@Target(value)
  • ElementType.TYPE 作用于类上面
  • ElementType.METHOD 作用于方法上面
  • ElementType.FIELD 作用于属性上面
  • 定义 Annotation 时,@Target 可有可无。若有 @Target,则该 Annotation 只能用于它所指定的地方;若没有 @Target,则该 Annotation 可以用于任何地方。
@Retention(RetentionPolicy.RUNTIME)

前面我们说过,RetentionPolicy 是 Annotation 的策略属性,而 @Retention 的作用,就是指定 Annotation 的策略属性。

@Retention(RetentionPolicy.RUNTIME) 的意思就是指定该 Annotation 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将该 Annotation 信息保留在 .class 文件中,并且能被虚拟机读取。

定义 Annotation 时,@Retention 可有可无。若没有 @Retention,则默认是 RetentionPolicy.CLASS。

@Documented

使用javadoc命令生成文档时 是否出现注解

@Deprecated

表明该方法或类已被弃用

简单使用自定义注解
通过注解参数实现需要调用的类名和方法名

demo1

public class demo1 {
    public void test(){
        System.out.println("demo1------test");
    }
}

demo2

public class demo2 {
    public void test(){
        System.out.println("demo2------test");
    }
}

@Pro

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();
}

Test类

import java.lang.reflect.Method;

@Pro(className = "com.study.annotation.demo2" , methodName = "test")
public class ProTest {
    public static void main(String[] args) {
        //获取字节码对象
        Class<ProTest> proTestClass = ProTest.class;

        //获取类上方的注解对象
        Pro annotation = proTestClass.getAnnotation(Pro.class);
        //获取到注解中所传递的参数
        String className = annotation.className();
        String methodName = annotation.methodName();

        try {
            //加载该类进内存
            Class aClass = Class.forName(className);
            //创建对象
            Object instance = aClass.newInstance();
            //获取方法对象
            Method method = aClass.getMethod(methodName);
            //执行方法
            method.invoke(instance);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值