java----Annotation
Annotation:
系统自带注解
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。public class Demo{ public static void main(String[] args) { Test test = new Test(); test.test(); //使用了不推荐使用的方法 } } //忽略编译期不当的警告 @SuppressWarnings("all") class Test{ //表示这个方法不再建议使用; @Deprecated public void test(){ System.out.println("方法已经过时"); } //检查此方法是不是覆盖了父类的方法 @Override public String toString() { return super.toString(); } }
自定义注解
import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; public class Demo{ public static void main(String[] args) throws IllegalAccessException, InstantiationException { Class<Cat> catClass = Cat.class; //获取类中应用的指定的注解 MyAnnotation annotation = catClass.getAnnotation(MyAnnotation.class); //通过反射获取注解中的值 String name = annotation.name(); int age = annotation.age(); String[] like = annotation.like(); Color color = annotation.color(); //实例化对象 Cat cat = catClass.newInstance(); cat.setAge(age); cat.setColor(color); cat.setLike(like); cat.setName(name); System.out.println(cat); } } //自定义注解 enum Color{ red,black; } //表示注解再运行时依然存在 @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation{ public String name(); public int age() default 10; //给变量设置默认值 public String[] like(); //定义一个数组变量 public Color color(); //定义一个枚举变量 } @MyAnnotation(name="bin",like = {"鱼",},color = Color.black) class Cat{ private String name; private String[] like; private Color color; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getLike() { return like; } public void setLike(String[] like) { this.like = like; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", like=" + Arrays.toString(like) + ", color=" + color + ", age=" + age + '}'; } }

更多精彩