[java]自定义注解demo

小鱼儿 2022-09-19 04:13 259阅读 0赞

1.自定义注解

  1. package annotation;
  2. import java.lang.annotation.Documented;
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7. @Target(ElementType.METHOD)
  8. @Retention(RetentionPolicy.RUNTIME)
  9. @Documented
  10. public @interface MyAnnotation {
  11. String name();
  12. int age();
  13. boolean sex();
  14. }

2.使用注解

  1. package annotation;
  2. import java.lang.reflect.Method;
  3. public class Student {
  4. private String name;
  5. private int age;
  6. private boolean sex;
  7. public void init(String name, int age, boolean sex) {
  8. this.name = name;
  9. this.age = age;
  10. this.sex = sex;
  11. }
  12. @MyAnnotation(name = "张三", age = 20, sex = true)
  13. public void init() {
  14. try {
  15. Method method = Student.class.getMethod("init");
  16. if (method.isAnnotationPresent(MyAnnotation.class)) {
  17. MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
  18. this.name = anno.name();
  19. this.age = anno.age();
  20. this.sex = anno.sex();
  21. }
  22. } catch (SecurityException e) {
  23. e.printStackTrace();
  24. } catch (NoSuchMethodException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. public void show() {
  29. System.out.print("{name=" + this.name);
  30. System.out.print(",age=" + this.age);
  31. System.out.println(",sex=" + (this.sex ? "男" : "女") + "}");
  32. }
  33. }

3.测试

  1. package annotation;
  2. public class StudentTest {
  3. public static void main(String[] args) throws Exception {
  4. Student stu = new Student();
  5. stu.init();
  6. stu.show();
  7. stu.init("李四", 21, false);
  8. stu.show();
  9. }
  10. }

4.打印结果

  1. {name=张三,age=20,sex=男}
  2. {name=李四,age=21,sex=女}

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java定义注解

    简介:     注解是在JDK5.0及以后版本中引入的。他可以用于创建文档,跟踪代码中的依赖性,甚至执行基本的编译时检查,而且还可以作为在spring框架中进行注解式注入Be

    相关 Java定义注解

    说到注解,也是面试中的重点高频知识点,因为利用注解加上反射可以做很多事情,通过注解对一些类或方法进行标示(override),通过注解、反射和AOP切面来做缓存,通过注解在类文