java—Annotation

Annotation是一种提供元数据描述的机制,可以为类、字段、方法、参数等程序元素添加元数据信息。Annotation能够在编译时进行处理,也可以在运行时通过Java反射机制获取它们的信息。

下面是一个Java SE中使用Annotation的示例:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String name();
    int age() default 20;
    String[] hobbies();
}

这个例子中,MyAnnotation是一个注解,它被定义为@Retention(RetentionPolicy.RUNTIME)和@Target(ElementType.METHOD),表示它在运行时依然存在,作用于方法上。该注解包含三个元素,分别为name、age和hobbies,其中age元素有一个默认值20。

以下是一个如何在方法上使用MyAnnotation的例子:

public class MyClass {
    @MyAnnotation(name = "John Smith", hobbies = {"reading", "writing"})
    public void myMethod() {
        // 方法体
    }
}

在这个例子中,我们为myMethod方法添加了MyAnnotation,为其添加了name和hobbies两个元素的值。根据上面的定义,age元素使用了默认值20。

我们可以使用反射机制获取MyAnnotation注解中的元素值,例如:

public class AnnotationDemo {
    public static void main(String[] args) throws Exception {
        MyClass obj = new MyClass();
        Method method = obj.getClass().getMethod("myMethod");
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        System.out.println("name: " + annotation.name());
        System.out.println("age: " + annotation.age());
        System.out.println("hobbies: ");
        for (String hobby : annotation.hobbies()) {
            System.out.println(hobby);
        }
    }
}

这个例子通过反射机制获取了myMethod方法上的MyAnnotation注解,并输出了所有的元素值。

运行上述代码,将会得到以下输出结果:

name: John Smith
age: 20
hobbies: 
reading
writing
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值