package javaAnnotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME) //生命周期--存活时间
@Target(FIELD) //运用的场景
public @interface fruitColor {
/*
* 颜色枚举
*/
public enum Color{
RED,
BLUE,
YELLOW,
GREEN,
WHITE
};
/**
* 颜色默认属性
* @return
*/
Color fruitColor() default Color.RED;
}
package javaAnnotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(FIELD)
public @interface fruitName {
String value() default "";
}
package javaAnnotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(FIELD)
public @interface fruitSeller {
/*
* 编号
*/
public int id() default 0;
/**
* 名称
* @return
*/
public String sellerName() default "";
/*
* 地址
*/
public String address() default "";
}
package javaAnnotation;
import java.lang.reflect.Field;
/**
* 注解处理
*/
public class FruitINFOS {
public static void getFruitInfos(Class<?> info) {
String FruitNames = "名称:";
String FruitColors = "颜色:";
String FruitSellers = "供应商:";
Field[] fields = info.getDeclaredFields();
for(Field field : fields) {
if(field.isAnnotationPresent(fruitName.class)) {
fruitName names = field.getAnnotation(fruitName.class);
FruitNames = FruitNames + names.value();
System.out.println(FruitNames);
}
if(field.isAnnotationPresent(fruitColor.class)) {
fruitColor colors = field.getAnnotation(fruitColor.class);
FruitColors = FruitColors + colors.fruitColor().toString();
System.out.println(FruitColors);
}
if(field.isAnnotationPresent(fruitSeller.class)) {
fruitSeller seller = field.getAnnotation(fruitSeller.class);
FruitSellers = "编号:" + seller.id() + ",供应商:" + seller.sellerName() +
",地址:" + seller.address();
System.out.println(FruitSellers);
}
}
}
}
package javaAnnotation;
public class Fruit {
@fruitName("apple")
private String Name;
@fruitColor(fruitColor = fruitColor.Color.YELLOW)
private String Color;
@fruitSeller(id=8,sellerName="ant",address="China")
private String Seller;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getColor() {
return Color;
}
public void setColor(String color) {
Color = color;
}
public String getSeller() {
return Seller;
}
public void setSeller(int ID, String seller, String Address) {
Seller = seller;
}
public void display() {
// FruitINFOS.getFruitInfos(getClass());
System.out.println("The fruit name is:" + Name);
}
}
测试类
package javaAnnotation;
public class BuyerFruit {
@SuppressWarnings("static-access")
public static void main(String[] args) {
FruitINFOS infos = new FruitINFOS();
infos.getFruitInfos(Fruit.class);
}
}