1.先定义一个自己的注解:
package com.zchen.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//元注解说明注解的生命周期
@Target({ElementType.METHOD,ElementType.TYPE})//在哪个位置定义注解
public @interface ZchenAnnotation {
}
2.将定义的注解加到要使用的位置
package com.zchen.annotation;
@ZchenAnnotation
public class AnnotationTest {
public static void main(String[] args) {
/**
* 检查类是否有注解——用反射机制
*/
if(AnnotationTest.class.isAnnotationPresent(ZchenAnnotation.class)){
ZchenAnnotation annotation = (ZchenAnnotation)AnnotationTest.class.getAnnotation(ZchenAnnotation.class);
System.out.println(annotation);
}
}
}
本文介绍了一种在Java中创建自定义注解的方法,并通过一个简单的例子展示了如何使用反射来检查类是否应用了该注解。
2832

被折叠的 条评论
为什么被折叠?



