java自定义注解

自定义注解

当我们理解了内置注解, 元注解和获取注解的反射接口后,我们便可以开始自定义注解了。
创建自定义注解和创建一个接口相似,但是注解的interface关键字需要以@符号开头,我们可以为注解声明方法。

格式:

// 元注解
public @interface 注解名称{
    // 属性列表
}

1、创建自定义注解

/**
 * 自定义注解
 *
 * @author Libbo
 */

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface TestAnnotation {
    String value();

    int maxLength() default 10000;
}

2、使用自定义注解

public class TestAnnotationClient {

    @TestAnnotation(value="Simple custom Annotation example")
    public void testHello(){
        System.out.println("Inside testHello method..");
    }
}

3、测试自定义注解

/**
 * @author Libbo
 * @description
 */
public class HelloAnnotationTest{

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        TestAnnotationClient helloAnnotationClient = new TestAnnotationClient();
        Method method = helloAnnotationClient.getClass().getMethod("sayHello");
        if(method.isAnnotationPresent(TestAnnotation.class)){
            TestAnnotation helloAnnotation=method.getAnnotation(TestAnnotation.class);
            //Get value of custom annotation
            System.out.println("Value : "+helloAnnotation.value());
            System.out.println("default : "+helloAnnotation.maxLength());
         
            method.invoke(helloAnnotationClient);
        }
    }

}
posted @ 2022-09-20 11:01  Libbo-yu  阅读(148)  评论(0编辑  收藏  举报