@Service
枚举:
让某个类型的变量只能取若干固定值中的一个,不然编译器会报错。可以控制源程序在编译期的赋值的非法不非法。
public enum Color {
RED,YELLO,GREEN
}
@Retention(RetentionPolicy.RUNTIME) //运行时有用
public @interface MyAnnotation {
public String name(); //定义变量,定义完变量后一定要给值。
public int age() default 2; //给了默认值为2
public String[] like(); //数组
public Color color(); //枚举
}
@Test
public void t2() throws InstantiationException, IllegalAccessException {
//反射处理注解
Class<Cat> catClass = Cat.class;
MyAnnotation annotation = catClass.getAnnotation(MyAnnotation.class);
int age = annotation.age();
Color color = annotation.color();
String[] like = annotation.like();
String name = annotation.name();
Cat cat = catClass.newInstance();
cat.setAge(age);
cat.setColor(color);
cat.setName(name);
cat.setLike(like);
System.out.println(cat);
}
@MyAnnotation(name="bilibili",like = {"fish","beef"},color = Color.GREEN)
public class Cat {
private String name;
private int age;
private String[] like;
private Color color;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", like=" + Arrays.toString(like) +
", color=" + color +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
}
@Deprecated
public String pringinf() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", like=" + Arrays.toString(like) +
", color=" + color +
'}';
}
public Cat() {
}
public Cat(String name, int age, String[] like, Color color) {
this.name = name;
this.age = age;
this.like = like;
this.color = color;
}
}