我要使用该注解的简单案例
时间: 2024-05-04 19:17:13 浏览: 10
好的,下面是一个简单的使用注解的案例:
假设你有一个类,其中包含了一个名为"add"的方法。你想要为这个方法添加一个注解,以便在运行时能够识别出来。首先,你需要定义一个注解:
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value();
}
```
这个注解定义了一个"value"属性,它可以用来设置注解的值。接下来,在你的类中,你可以为"add"方法添加这个注解:
```java
public class MyClass {
@MyAnnotation("This is my method")
public int add(int a, int b) {
return a + b;
}
}
```
现在,当你在运行时调用"add"方法时,你可以使用反射来获取这个注解:
```java
MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("add", int.class, int.class);
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
```
这段代码将输出:"This is my method",这就是你在注解中设置的值。