Java注解(二)

前面了解了注解的基本内容,这次来看一下自定义注解。

自定义注解其实很简单,直接上代码:

复制代码
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
/*
 * 定义注解 Test
 * 注解中含有两个元素 id 和 description
 * description 元素 有默认值 "hello anntation"
 */
public @interface Test {
    public int id();
    public String description() default "hello annotation";
}
复制代码

 根据上一篇对元注解的解释,我们知道:

  1. 这个注解可以用于方法
  2. JVM运行期间该注解都有效
  3. 该注解包含在 javadoc 中
  4. 该注解允许子类继承

 下面看下通过注解我们能取到什么

复制代码
public class TestMain {  
    /* 
     * 被注解的三个方法 
     */  
    @Test(id = 1, description = "hello methodA")  
    public void methodA() {  
    }  
  
    @Test(id = 2)  
    public void methodB() {  
    }  
  
    @Test(id = 3, description = "last method")  
    public void methodC() {  
    }  
  
    /* 
     * 解析注解,将类被注解方法 的信息打印出来 
     */  
    public static void main(String[] args) {  
        Method[] methods = TestMain.class.getDeclaredMethods();  
        for (Method method : methods) {  
            /* 
             * 判断方法中是否有指定注解类型的注解 
             */  
            boolean hasAnnotation = method.isAnnotationPresent(Test.class);  
            if (hasAnnotation) {  
                /* 
                 * 根据注解类型返回方法的指定类型注解 
                 */  
                Test annotation = method.getAnnotation(Test.class);  
                System.out.println("Test( method = " + method.getName() + " , id = " + annotation.id() 
                        + " , description = " + annotation.description() + " )");
            }  
        }  
    }  
} 
复制代码

 上面的Demo打印的结果如下:

Test( method = methodA , id = 1 , description = hello methodA )
Test( method = methodB , id = 2 , description = hello annotation )
Test( method = methodC , id = 3 , description = last method )

 上例其实也说明了,我们一般通过反射来取RUNTIME保留策略的注解信息。

 

 

 

posted @   yejg1212  阅读(1050)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示