共計 796 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以通過定義一個注解類來自定義注解,并在需要使用的地方調用該注解。下面是一個簡單的示例:
- 定義一個自定義注解類:
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)
public @interface MyAnnotation {String value();
}
- 在需要使用注解的地方調用該注解:
public class MyClass {@MyAnnotation("Hello, World!")
public void myMethod() {// do something
}
public static void main(String[] args) {MyClass myClass = new MyClass();
try {// 獲取方法上的注解
MyAnnotation annotation = myClass.getClass().getMethod("myMethod").getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
} catch (NoSuchMethodException e) {e.printStackTrace();
}
}
}
在上面的示例中,定義了一個名為 MyAnnotation
的自定義注解,并在 myMethod
方法上使用了該注解。在 main
方法中通過反射獲取 myMethod
方法上的注解,并輸出注解的值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2024-05-27