直接上例子,新建Java Project
1.新建Interface,建完在名字前加@,就成了自定义的注解
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
-
-
-
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface OneAnnotation {
-
-
- String parameter1() default "";
- int parameter2() default -1;
- }
2.使用注解的类
-
-
-
- public class OneClass {
-
- @OneAnnotation(parameter1="YES", parameter2=10000)
- public void oneMethod () {
- }
- }
3.提取注解参数
- import java.lang.reflect.Method;
-
-
- public class TestThis {
-
- public static void main(String[] args) throws Exception {
-
- Method method = Class.forName("OneClass").getDeclaredMethod("oneMethod");
-
- OneAnnotation oneAnnotation = method.getAnnotation(OneAnnotation.class);
-
-
- System.out.println(oneAnnotation.parameter1());
- System.out.println(oneAnnotation.parameter2());
- }
- }
测试结果:
YES
10000