注解是元数据

注解是一种装饰器、一个标记(maker),应用于Java的各种结构之上,例如类、方法、字段。用来为这些结构绑定元数据。注解不包含任何业务逻辑

只由运行时框架或编译器根据注解信息去执行具体行为。

Retention and Target

保留(Retention )策略指定就程序生命周期而言,注释应该保留多长时间(一个)

目标(Target)指定注解可以应用于哪些Java结构 (多个)



自定义annotation

@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"}

总结

虽然注解不应该用来代替接口或其他以面向对象的方式正确完成任务的语言结构,但它们可以极大地简化重复的逻辑。

利用注解,可以以声明式的编程方式,将与具体业务领域无关的功能(安全、事务、日志)等抽离出来。实现不同逻辑的解耦。

Java 注解(Annotations) 详解的更多相关文章

  1. Java注解(Annotation)详解

    转: Java注解(Annotation)详解 幻海流心 2018.05.23 15:20 字数 1775 阅读 380评论 0喜欢 1 Java注解(Annotation)详解 1.Annotati ...

  2. Java 注解用法详解——@SuppressWarnings

    转自: https://www.cnblogs.com/fsjohnhuang/p/4040785.html Java魔法堂:注解用法详解——@SuppressWarnings   一.前言 编码时我 ...

  3. Java注解Annotation详解

    从JDK5开始,Java增加了Annotation(注解),Annotation是代码里的特殊标记,这些标记可以在编译.类加载.运行时被读取,并执行相应的处理.通过使用Annotation,开发人员可 ...

  4. Android注解支持Support Annotations详解

    ###注解支持(Support Annotations)Android support library从19.1版本开始引入了一个新的注解库,它包含很多有用的元注解,你能用它们修饰你的代码,帮助你发现 ...

  5. 转:springmvc常用注解标签详解

    Spring5:@Autowired注解.@Resource注解和@Service注解 - IT·达人 - 博客园--这篇顺序渐进,讲得超级好--此人博客很不错http://www.cnblogs.c ...

  6. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  7. Java 序列化Serializable详解

    Java 序列化Serializable详解(附详细例子) Java 序列化Serializable详解(附详细例子) 1.什么是序列化和反序列化Serialization(序列化)是一种将对象以一连 ...

  8. Java String类详解

    Java String类详解 Java字符串类(java.lang.String)是Java中使用最多的类,也是最为特殊的一个类,很多时候,我们对它既熟悉又陌生. 类结构: public final ...

  9. 最新java数组的详解

    java中HashMap详解 http://alex09.iteye.com/blog/539545 总结: 1.就像引用类型的数组一样,当我们把 Java 对象放入数组之时,并不是真正的把 Java ...

随机推荐

  1. ValueError: row index was 65536, not allowed by .xls format

    报错:ValueError: row index was 65536, not allowed by .xls format 读取.xls文件正常,在写.xls文件,pd.to_excel()时候会报 ...

  2. PHP和js判断访问设备是否是微信浏览器实例

    PHP和js判断访问设备是否是微信浏览器实例,代码非常精简,适合新手学习. js判断是否是微信浏览器: 1 function is_weixin() { 2 var ua = window.navig ...

  3. shell习题第17题:检测磁盘

    [题目要求] 写一个shell脚本,检测所有磁盘分区使用率和inode使用率并记录到以当天日期命名的日志文件里,当发现某个分区容量或者inode使用量大于85%时候,发邮件提醒 [核心要点] df d ...

  4. nginx日志模块、事件模块

    日志模块 1.access_log指令 语法: access_log path [format [buffer=size [flush=time]]]; access_log logs/access. ...

  5. .Net C# RSA签名和验签

    帮助类 using System; using System.Text; using System.IO; using System.Security.Cryptography; namespace ...

  6. Spring在Thread中注入Bean无效的解决方式

    在Spring项目中,有时需要新开线程完成一些复杂任务,而线程中可能需要注入一些服务.而通过Spring注入来管理和使用服务是较为合理的方式.但是若直接在Thread子类中通过注解方式注入Bean是无 ...

  7. Redis 的订阅发布(PUB/SUB)示例

    ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1"); ISubscriber sub ...

  8. 网络编程之NIO

    传统的BIO(Blocking IO)的缺点: 1.基于阻塞式IO建立起来的,导致服务端一直阻塞等待着客户端发起请求,如果客户端不发起,服务端的的业务线程会一直存. 2.弹性伸缩能力差,线程数和客户端 ...

  9. 网易云音乐ncm加密格式批量转换为flac,mp3

    从网易云下载的某些付费歌曲下载下来会是ncm格式.ncm是个啥?就是你下完一首歌被网易云加密成它自己独有的ncm格式,这个ncm不能在其他播放器播放,如果网易云你会员到期了同样也会提示你无法播放(不是 ...

  10. C++ STL 之 deque容器 打分案例(内含sort排序用法)

    #include <iostream> #include <vector> #include <time.h> #include <deque> #in ...