本文將從如下幾點爲你介紹java註解以及如何自定義java
Java註解在平常開發中常常遇到,但一般咱們只是用它,難道你不會好奇註解是怎麼實現的嗎?爲何@Data的註解能夠生成getter和setter呢?爲何@BindView能夠作到不須要findViewById呢?爲何retrofit2只要寫個接口就能夠作網絡請求呢?本文將爲你一一解答其中的奧妙。另外註解依賴於反射,我相信絕大多數的Java開發者都寫過反射,也都知道反射是咋回事,因此若是你還不理解反射,請先花幾分鐘熟悉後再閱讀本文。git
Annotation也叫元數據,是代碼層面的說明。它在JDK1.5之後被引入,與類、接口、枚舉是在同一個層次。它能夠聲明在包、類、字段、方法、局部變量、方法參數等的前面,用來對這些元素進行說明,註釋。咱們能夠簡單的理解註解只是一種語法標註,它是一種約束、標記。程序員
在JDK1.5之前,描述元數據都是使用xml的,可是xml老是表現出鬆散的關聯度,致使文件過多時難以維護,好比Spring早期的注入xml。所以Java1.5引入註解最大的緣由就是想把元數據與代碼強關聯,好比Spring 2.0大多轉爲註解注入。 雖然註解作到了強關聯,可是一些常量參數使用xml會顯結構更加清晰,因此在平常使用時,老是會把xml和Annotation結合起來使用以達到最優使用。github
一般咱們會按照註解的運行機制將其分類,可是在按照註解的運行機制分類以前,咱們先按基本分類來看一遍註解。bash
主要是按照元註解中的@Retention參數將其分爲三類網絡
咱們能夠簡單的把Java程序從源文件建立到程序運行的過程看做爲兩大步驟app
那麼被標記爲RetentionPolicy.SOURCE的註解只能保留在源碼級別,即最多隻能在源碼中對其操做,被標記爲RetentionPolicy.CLASS的被保留到字節碼,因此最多隻到字節碼級別操做,那麼對應的RetentionPolicy.RUNTIME能夠在運行時操做。框架
前面的都是司空見慣的知識點,可能你們都知道或有有了解過,可是一說到自定義,估計夠嗆,那麼下面就按運行機制的分類,每一類都自定義一個註解看下註解究竟是怎麼回事。ide
運行時註解一般須要先經過類的實例反射拿到類的屬性、方法等,而後再遍歷屬性、方法獲取位於其上方的註解,而後就能夠作相應的操做了。 好比如今有一個Person的接口以及其實現類Student。工具
public interface Person {
@PrintContent("來自注解 PrintContent 唱歌")
void sing(String value);
@PrintContent("來自注解 PrintContent 跑步")
void run(String value);
@PrintContent("來自注解 PrintContent 吃飯")
void eat(String value);
@PrintContent("來自注解 PrintContent 工做")
void work(String value);
}
複製代碼
實現類
public class Student implements Person {
@Override
public void sing(String value) {
System.out.println(value == null ? "這是音樂課,咱們在唱歌" : value);
}
@Override
public void run(String value) {
System.out.println(value == null ? "這是體育課,咱們在跑步" : value);
}
@Override
public void eat(String value) {
System.out.println(value == null ? "中午咱們在食堂吃飯" : value);
}
@Override
public void work(String value) {
System.out.println(value == null ? "咱們的工做是學習" : value);
}
}
複製代碼
執行邏輯
@Autowired
private Person person;
public void student() {
person.eat(null);
person.run(null);
person.sing(null);
person.work(null);
}
複製代碼
咱們須要實現的點
由於這是一個運行時的註解,因此咱們須要反射先拿到這個註解,而後再對其進行操做。 Autowired的實現,能夠看到很是簡單,僅僅是先拿到類的全部屬性,而後對其遍歷,發現屬性使用了Autowired註解而且是Person類型,那麼就new一個Student爲其賦值,這樣就作到了自動注入的效果。
private static void inject(Object obj) {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if (field.getType() == Person.class) {
if (field.isAnnotationPresent(Autowired.class)) {
field.setAccessible(true);
try {
Person student = new Student();
field.set(obj, student);
} catch (IllegalAccessException e) {
e.printStackTrace();
}}}
}}
複製代碼
若是是想當value爲null時打印的註解的默認值,並在調用的方法先後插入本身想作的操做。這種對接口方法進行攔截並操做的稱爲動態代理,java提供Proxy.newProxyInstance支持。
private static void inject(Object obj) {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if (field.getType() == Person.class) {
if (field.isAnnotationPresent(Autowired.class)) {
field.setAccessible(true);
try {
Person student = new Student();
Class<?> cls = student.getClass();
Person person = (Person) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), new DynamicSubject(student));
field.set(obj, person);
} catch (IllegalAccessException e) {
e.printStackTrace();
}}}
}}
複製代碼
其中須要自定義DynamicSubject,即對方法的真實攔截操做。這樣就會把@PrintContent註解的值做爲參數打印處理。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.isAnnotationPresent(PrintContent.class)) {
PrintContent printContent = method.getAnnotation(PrintContent.class);
System.out.println(String.format("----- 調用 %s 以前 -----", method.getName()));
method.invoke(object, printContent.value());
System.out.println(String.format("----- 調用 %s 以後 -----\n", method.getName()));
return proxy;
}
return null;
}
複製代碼
最後附上兩個自定義的註解
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PrintContent {
String value();
}
複製代碼
以上能夠幫助你對retorfit2的理解,由於動態代理就是它的核心之一。若是你想學習更多,能夠參考仿retorfit2設計實現的Activity參數注入
你們或許對@BindView生成代碼有所懷疑,對@Data如何生成代碼有所好奇,那麼咱們就自定義個@Data來看看怎麼註解是怎麼生成代碼的。本文依賴於idea工具,並不是google提供的@AutoService實現。 bean是開發中常常被使用的,getter、setter方法是被咱們所厭棄寫的,idea幫咱們作了一鍵生成的插件工具,可是若是這一步都都不想操做呢?我只想用一個註解生成,好比下面的User類。
@Data
public class User {
private Integer age;
private Boolean sex;
private String address;
private String name;
}
複製代碼
經過@Data就能夠生成這樣的類,是否是很神奇?
public class User{
private Integer age;
private Boolean sex;
private String address;
private String name;
public User() {
}
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean hasSex() {
return this.sex;
}
public void isSex(Boolean sex) {
this.sex = sex;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
複製代碼
要實現這樣的神奇操做,大概的思路是先自定義某個RetentionPolicy.SOURCE級別的註解,而後實現一個註解處理器並設置SupportedAnnotationTypes爲當前的註解,最後在META-INF註冊該註解處理器。因此首先咱們定義Data註解。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@Documented
public @interface Data {
}
複製代碼
而後須要自定義註解處理器來處理Data註解
@SupportedAnnotationTypes("com.data.Data")
public class DataProcessor extends AbstractProcessor {
}
複製代碼
而後在resources/META-INF文件夾下新建services文件夾,若是沒有META-INF也新建。而後在services文件夾裏新建javax.annotation.processing.Processor文件,注意名字是固定的,打開文件後寫上前面定義的註解處理器全稱,好比com.data.DataProcessor,這樣就表示該註解處理器被註冊了。 待程序要執行的時候,編譯器會先讀取這裏的文件而後掃描整個工程,若是工程中有使用已註冊的註解處理器中的SupportedAnnotationTypes裏的註解,那麼就會執行對應的註解處理中的process方法。下面重點處理註解處理器AbstractProcessor,把大部分的解釋都寫在註解裏。
@SupportedAnnotationTypes("com.data.Data")
public class DataProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "-----開始自動生成源代碼");
try {
// 返回被註釋的節點
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Data.class);
for (Element e : elements) {
// 若是註釋在類上
if (e.getKind() == ElementKind.CLASS && e instanceof TypeElement) {
TypeElement element = (TypeElement) e;
// 類的全限定名
String classAllName = element.getQualifiedName().toString() + "New";
// 返回類內的全部節點
List<? extends Element> enclosedElements = element.getEnclosedElements();
// 保存字段的集合
Map<Name, TypeMirror> fieldMap = new HashMap<>();
for (Element ele : enclosedElements) {
if (ele.getKind() == ElementKind.FIELD) {
//字段的類型
TypeMirror typeMirror = ele.asType();
//字段的名稱
Name simpleName = ele.getSimpleName();
fieldMap.put(simpleName, typeMirror);
}
}
// 生成一個Java源文件
String targetClassName = classAllName;
if (classAllName.contains(".")) {
targetClassName = classAllName.substring(classAllName.lastIndexOf(".") + 1);
}
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(targetClassName);
// 寫入代碼
createSourceFile(classAllName, fieldMap, sourceFile.openWriter());
} else {
return false;
}
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "-----完成自動生成源代碼");
return true;
}
/**
* 屬性首字母大寫
*/
private String humpString(String name) {
String result = name;
if (name.length() == 1) {
result = name.toUpperCase();
}
if (name.length() > 1) {
result = name.substring(0, 1).toUpperCase() + name.substring(1);
}
return result;
}
private void createSourceFile(String className, Map<Name, TypeMirror> fieldMap, Writer writer) throws IOException {
// 檢查屬性是否以 "get", "set", "is", "has" 這樣的關鍵字開頭,若是有這樣的 屬性就報錯
String[] errorPrefixes = {"get", "set", "is", "has"};
for (Map.Entry<Name, TypeMirror> map : fieldMap.entrySet()) {
String name = map.getKey().toString();
for (String prefix : errorPrefixes) {
if (name.startsWith(prefix)) {
throw new RuntimeException("Properties do not begin with 'get'、'set'、'is'、'has' in " + name);
}
}
}
String packageName;
String targetClassName = className;
if (className.contains(".")) {
packageName = className.substring(0, className.lastIndexOf("."));
targetClassName = className.substring(className.lastIndexOf(".") + 1);
} else {
packageName = "";
}
// 生成源代碼
JavaWriter jw = new JavaWriter(writer);
jw.emitPackage(packageName);
jw.beginType(targetClassName, "class", EnumSet.of(Modifier.PUBLIC));
jw.emitEmptyLine();
for (Map.Entry<Name, TypeMirror> map : fieldMap.entrySet()) {
String name = map.getKey().toString();
String type = map.getValue().toString();
//字段
jw.emitField(type, name, EnumSet.of(Modifier.PRIVATE));
jw.emitEmptyLine();
}
for (Map.Entry<Name, TypeMirror> map : fieldMap.entrySet()) {
String name = map.getKey().toString();
String type = map.getValue().toString();
String prefixGet = "get";
String prefixSet = "set";
if (type.equals("java.lang.Boolean")) {
prefixGet = "has";
prefixSet = "is";
}
//getter
jw.beginMethod(type, prefixGet + humpString(name), EnumSet.of(Modifier.PUBLIC))
.emitStatement("return " + name)
.endMethod();
jw.emitEmptyLine();
//setter
jw.beginMethod("void", prefixSet + humpString(name), EnumSet.of(Modifier.PUBLIC), type, name)
.emitStatement("this." + name + " = " + name)
.endMethod();
jw.emitEmptyLine();
}
jw.endType().close();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
複製代碼
至此整個Data的註解生成器就寫完了,因爲咱們的idea沒有對應的插件幫助咱們作一些操做,因此生成的類編譯生成字節碼時會報已存在異常,因此若是你想更進一步,能夠考慮寫個插件,本文僅限註解,未提供這樣的插件。 以上完成後,只要在data class頭添加@Data註解,在編譯程序以前,就能夠看到target/classes中存在了咱們生成的代碼。至此你應該瞭解@BindView或者@Data的原理,或許你也能夠嘗試自定義一個ButterKnife框架。
字節碼級別的實際上對應用程序員來講沒多大做用,由於此類註解通常是在字節碼文件上進行操做,咱們通常理解整個過程是在.java編譯爲.class後在將要被加載到虛擬機以前。那麼很顯然RetentionPolicy.CLASS類別的註解是直接修改字節碼文件的。因此通常用此註解須要底層開發人員的配合,或者當你須要造輪子了能夠考慮用一下,不過須要ASM的配合來使用的,若是僅僅是開發應用基本用不到。 不過這裏仍是介紹下它的使用,先造場景:如今有個People類,其中有個size屬性等於9,觀察到上方的類註解是@Prinln(12),如今想在字節碼層面把size的9替換爲12。
@Prinln(12)
public class People {
int size = 9;
double phone = 12.0;
Boolean sex;
String name;
}
複製代碼
因爲咱們並不知道字節碼文件是怎麼寫的,因此須要先經過Show Bytecode的插件來查看類的字節碼是啥樣子的
// class version 52.0 (52)
// access flags 0x21
public class com/People {
// compiled from: People.java
@Lcom/ann/Prinln;(value=12) // invisible
// access flags 0x0
I size
// access flags 0x2
private D phone
// access flags 0x2
private Ljava/lang/Boolean; sex
// access flags 0x2
private Ljava/lang/String; name
// access flags 0x1
public <init>()V
L0
LINENUMBER 12 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
L1
LINENUMBER 14 L1
ALOAD 0
BIPUSH 9
PUTFIELD com/People.size : I
L2
LINENUMBER 16 L2
ALOAD 0
LDC 12.0
PUTFIELD com/People.phone : D
RETURN
L3
LOCALVARIABLE this Lcom/People; L0 L3 0
MAXSTACK = 3
MAXLOCALS = 1
}
複製代碼
雖然知道了是這樣的,但仍是看不懂啊,咋整呢?不要緊,咱們看ASMified。ASM 是一個 Java 字節碼操控框架。它能被用來動態生成類或者加強既有類的功能。ASM 能夠直接產生二進制 class 文件,也能夠在類被加載入 Java 虛擬機以前動態改變類行爲。並且ASMified咱們是能夠看得懂的,雖然沒學過,可是很好理解。好比上面的People的ASMified就是這樣的。
public class PeopleDump implements Opcodes {
public static byte[] dump() throws Exception {
ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;
cw.visit(52, ACC_PUBLIC + ACC_SUPER, "com/People", null, "java/lang/Object", null);
cw.visitSource("People.java", null);
{
av0 = cw.visitAnnotation("Lcom/ann/Prinln;", false);
av0.visit("value", new Integer(12));
av0.visitEnd();
}
{
fv = cw.visitField(0, "size", "I", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(ACC_PRIVATE, "phone", "D", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(ACC_PRIVATE, "sex", "Ljava/lang/Boolean;", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(ACC_PRIVATE, "name", "Ljava/lang/String;", null, null);
fv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(12, l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLineNumber(14, l1);
mv.visitVarInsn(ALOAD, 0);
mv.visitIntInsn(BIPUSH, 9);
mv.visitFieldInsn(PUTFIELD, "com/People", "size", "I");
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLineNumber(16, l2);
mv.visitVarInsn(ALOAD, 0);
mv.visitLdcInsn(new Double("12.0"));
mv.visitFieldInsn(PUTFIELD, "com/People", "phone", "D");
mv.visitInsn(RETURN);
Label l3 = new Label();
mv.visitLabel(l3);
mv.visitLocalVariable("this", "Lcom/People;", null, l0, l3, 0);
mv.visitMaxs(3, 1);
mv.visitEnd();
}
cw.visitEnd();
return cw.toByteArray();
}
}
複製代碼
這樣的話,咱們大概能夠知道若是要改size=12,就只要把mv.visitIntInsn(BIPUSH, 9);這句話的9改成12就行了。不過ASM在原有的字節碼文件中插入或刪除或更改,本文未仔細研究。本文是簡單粗暴的用新的字節碼替換原字節碼文件。
public void asm() {
try {
ClassReader classReader = new ClassReader(new FileInputStream("target/classes/com/People.class"));
ClassNode classNode = new ClassNode();
classReader.accept(classNode, ClassReader.SKIP_DEBUG);
System.out.println("Class Name: " + classNode.name);
AnnotationNode anNode = null;
if (classNode.invisibleAnnotations.size() == 1) {
anNode = classNode.invisibleAnnotations.get(0);
System.out.println("Annotation Descriptor : " + anNode.desc);
System.out.println("Annotation attribute pairs : " + anNode.values);
}
File file = new File("target/classes/com/People.class");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(copyFromBytecode(anNode == null ? 0 : (int) anNode.values.get(1)));
} catch (IOException e) {
e.printStackTrace();
}
People people = new People();
System.out.println("people : " + people.size);
}
private byte[] copyFromBytecode(int value) {
ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;
cw.visit(52, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "com/People", null, "java/lang/Object", null);
cw.visitSource("People.java", null);
{
av0 = cw.visitAnnotation("Lcom.ann.Prinln;", false);
av0.visit("value", new Integer(12));
av0.visitEnd();
}
{
fv = cw.visitField(0, "size", "I", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(0, "phone", "D", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(0, "sex", "Ljava/lang/Boolean;", null, null);
fv.visitEnd();
}
{
fv = cw.visitField(0, "name", "Ljava/lang/String;", null, null);
fv.visitEnd();
}
{
mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(10, l0);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLineNumber(12, l1);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitIntInsn(Opcodes.BIPUSH, value);
mv.visitFieldInsn(Opcodes.PUTFIELD, "com/People", "size", "I");
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLineNumber(14, l2);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitLdcInsn(new Double("12.0"));
mv.visitFieldInsn(Opcodes.PUTFIELD, "com/People", "phone", "D");
mv.visitInsn(Opcodes.RETURN);
Label l3 = new Label();
mv.visitLabel(l3);
mv.visitLocalVariable("this", "Lcom/People;", null, l0, l3, 0);
mv.visitMaxs(3, 1);
mv.visitEnd();
}
cw.visitEnd();
return cw.toByteArray();
}
複製代碼
實際上RetentionPolicy.CLASS的使用,ASM的配合很重要,因此當你在本身的框架中須要使用這種類型的註解的時候,建議仍是學好ASM再嘗試寫此類註解,而不是像我這樣所有替換。
本文註解雖然講解的多,可是若是你能看完到這裏,相信經過了幾個例子的描述,你已經知道了幾類註解的基本操做過程,已經讓你對各類類型的註解有基本的認識,或許看了本文你真的理解了retrofit二、ButterKnife,甚至能夠本身寫個簡單的retrofit2或ButterKnife的框架,那就再好不過了。 最後附上源碼,感謝閱讀。
本文版權屬於再惠研發團隊,歡迎轉載,轉載請保留出處。@Dpuntu