帶你入門Java註解
本文將從以下幾點為你介紹java註解以及如何自定義
- 引言
- 註解定義
- 註解意義
- 註解分類
- 自定義
- 結束語
引言
Java註解在日常開發中經常遇到,但通常我們只是用它,難道你不會好奇註解是怎麼實現的嗎?為什麼@Data的註解可以生成getter和setter呢?為什麼@BindView可以做到不需要findViewById呢?為什麼retrofit2只要寫個介面就可以做網路請求呢?本文將為你一一解答其中的奧妙。另外註解依賴於反射,我相信絕大多數的Java開發者都寫過反射,也都知道反射是咋回事,所以如果你還不理解反射,請先花幾分鐘熟悉後再閱讀本文。
註解定義
Annotation也叫元資料,是程式碼層面的說明。它在JDK1.5以後被引入,與類、介面、列舉是在同一個層次。它可以宣告在包、類、欄位、方法、區域性變數、方法引數等的前面,用來對這些元素進行說明,註釋。我們可以簡單的理解註解只是一種語法標註,它是一種約束、標記。
註解意義
Java引入註解是想把某些元資料做到與程式碼強耦合。因為在JDK1.5以前,描述元資料都是使用xml的,但是xml總是表現出鬆耦合,導致檔案過多時難以維護。比如Spring早期的注入xml,如今2.0大多轉為註解注入。 雖然註解做到了強耦合,但是一些常量引數使用xml會顯結構更加清晰,所以在日常使用時,總是會把xml和Annotation結合起來使用以達到最優使用。
註解分類
通常我們會按照註解的執行機制將其分類,但是在按照註解的執行機制分類之前,我們先按基本分類來看一遍註解。
基本分類
-
內建註解(基本註解)
內建註解只有三個,位於java.lang包下,他們分別是
- @Override - 檢查該方法是否是過載方法,如果發現其父類,或者是引用的介面中並沒有該方法時,會報編譯錯誤。
- @Deprecated - 標記過時方法,如果使用該方法,會報編譯警告。
- @SuppressWarnings - 指示編譯器去忽略註解中宣告的警告。
-
元註解
元註解只有四個,位於java.lang.annotation包中
- @Retention - 標識這個註解怎麼儲存,是隻在程式碼中,還是編入class檔案中,或者是在執行時可以通過反射訪問
- @Documented - 標記這些註解是否包含在使用者文件中
-
@Target - 標記這個註解應該是哪種 Java 成員
- ElementType.CONSTRUCTOR構造方法宣告
- ElementType.FIELD欄位宣告
- ElementType.LOCAL_VARIABLE區域性變數宣告
- ElementType.METHOD方法宣告
- ElementType.PACKAGE包宣告
- ElementType.PARAMETER引數宣告
- ElementType.TYPE類、介面方法
- @Inherited - 標記註解可繼承
- 自定義註解 可以通過元註解來自定義
執行機制分類
主要是按照元註解中的@Retention引數將其分為三類
- 原始碼註解(@Retention(RetentionPolicy.SOURCE)) 註解只在原始碼中存在,編譯時丟棄,編譯成.class檔案就不存在了
- 編譯時註解(@Retention(RetentionPolicy.CLASS)) 編譯時會記錄到.class中,執行時忽略
- 執行時註解(@Retention(RetentionPolicy.RUNTIME)) 執行時存在起作用,影響執行邏輯,可以通過反射讀取
我們可以簡單的把Java程式從原始檔建立到程式執行的過程看作為兩大步驟
- 原始檔由編譯器編譯成位元組碼
- 位元組碼由java虛擬機器解釋執行
那麼被標記為RetentionPolicy.SOURCE的註解只能保留在原始碼級別,即最多隻能在原始碼中對其操作,被標記為RetentionPolicy.CLASS的被保留到位元組碼,所以最多隻到位元組碼級別操作,那麼對應的RetentionPolicy.RUNTIME可以在執行時操作。
自定義
前面的都是司空見慣的知識點,可能大家都知道或有有了解過,但是一說到自定義,估計夠嗆,那麼下面就按執行機制的分類,每一類都自定義一個註解看下註解到底是怎麼回事。
RetentionPolicy.RUNTIME
執行時註解通常需要先通過類的例項反射拿到類的屬性、方法等,然後再遍歷屬性、方法獲取位於其上方的註解,然後就可以做相應的操作了。 比如現在有一個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表示自動注入Student物件給person。
- 提供方法註解@PrintContent表示當value為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引數注入
RetentionPolicy.SOURCE
大家或許對@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框架。
RetentionPolicy.CLASS
位元組碼級別的實際上對應用程式設計師來說沒多大作用,因為此類註解一般是在位元組碼檔案上進行操作,我們一般理解整個過程是在.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再嘗試寫此類註解,而不是像我這樣全部替換。
結束語
本文註解雖然講解的多,但是如果你能看完到這裡,相信通過了幾個例子的描述,你已經知道了幾類註解的基本操作過程,已經讓你對各種型別的註解有基本的認識,或許看了本文你真的理解了retrofit2、ButterKnife,甚至可以自己寫個簡單的retrofit2或ButterKnife的框架,那就再好不過了。 最後附上原始碼 ,感謝閱讀。