java怎么自定义注解调用方法

16次阅读
没有评论

共计 796 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以通过定义一个注解类来自定义注解,并在需要使用的地方调用该注解。下面是一个简单的示例:

  1. 定义一个自定义注解类:
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();
}
  1. 在需要使用注解的地方调用该注解:
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 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-27发表,共计796字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)