注解是一种装饰器、一个标记(maker),应用于Java的各种结构之上,例如类、方法、字段。用来为这些结构绑定元数据。注解不包含任何业务逻辑。
只由运行时框架或编译器根据注解信息去执行具体行为。
保留(Retention )策略指定就程序生命周期而言,注释应该保留多长时间(一个)
目标(Target)指定注解可以应用于哪些Java结构 (多个)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonField {
public String value() default "";
}
public class Car {
@JsonField("manufacturer")
private final String make;
@JsonField
private final String model;
private final String year;
public Car(String make, String model, String year) {
this.make = make;
this.model = model;
this.year = year;
}
## get and set method
@Override
public String toString() {
return year + " " + make + " " + model;
}
}
利用反射机制执行具体行为
public class JsonSerializer {
public String serialize(Object object) throws JsonSerializeException {
try {
Class<?> objectClass = requireNonNull(object).getClass();
Map<String, String> jsonElements = new HashMap<>();
for (Field field: objectClass.getDeclaredFields()) {
field.setAccessible(true);
if (field.isAnnotationPresent(JsonField.class)) {
jsonElements.put(getSerializedKey(field), (String)field.get(object));
}
}
System.out.println(toJsonString(jsonElements));
return toJsonString(jsonElements);
} catch (IllegalAccessException e) {
throw new JsonSerializeException(e.getMessage());
}
}
private String toJsonString(Map<String, String> jsonMap) {
String elementsString = jsonMap.entrySet()
.stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(","));
return "{" + elementsString + "}";
}
private String getSerializedKey(Field field) {
String annotationValue = field.getAnnotation(JsonField.class).value();
if (annotationValue.isEmpty()) {
return field.getName();
} else {
return annotationValue;
}
}
}
Car car = new Car("Ford", "F150", "2018");
JsonSerializer serializer = new JsonSerializer();
serializer.serialize(car);
# output
# {"model":"F150","manufacturer":"Ford"}
虽然注解不应该用来代替接口或其他以面向对象的方式正确完成任务的语言结构,但它们可以极大地简化重复的逻辑。
利用注解,可以以声明式的编程方式,将与具体业务领域无关的功能(安全、事务、日志)等抽离出来。实现不同逻辑的解耦。
原文:https://www.cnblogs.com/yeni/p/12082873.html