We often see in the Java code: "@Override", "@Target" and so on the appearance of things, what are these?
In Java they are "annotations".
The following is the explanation of Baidu Encyclopedia: Java.lang.annotation.Retention can instruct the compiler how to treat your custom annotation when you define annotation patterns. By default, the compiler leaves the annotation information in the class file, but is not read by the virtual machine, only for information provided by the compiler or tool runtime.
In other words, annotations are based on the class file, and the C-language macro has the same effect.
The class file does not see traces of annotations at all.
The basis of annotations is reflection. So annotations can be understood as a Java-specific concept.
1. Meta-annotation
In the Java.lang.annotation package, 4 kinds of annotation have been defined as "primitives".
1. @Target, for explicitly modified types: (Methods, fields, classes, interfaces, etc.)
2). @Retention, describe the existence of anntation so far:
The retentionpolicy.runtime annotation is present in the class bytecode file and can be obtained by reflection at run time
Retentionpolicy.class The default retention policy, annotations are present in the CLASS bytecode file, but cannot be obtained at run time
Retentionpolicy.source annotations exist only in the source code and are not included in the class byte code file
3. @Documented, annotations are not recorded in Javadoc by default, but this annotation can be used to indicate that the annotation needs to be logged.
4. @Inherited Meta annotation is a markup annotation, @Inherited illustrates that a labeled type is inherited.
If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.
2. Custom annotations
Package com.joyfulmath.jvmexample.annnotaion;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
/**
* @author deman.lu
* @version on 2016-05-23 13:36 * * *
@Target (Elementtype.field)
@ Retention (retentionpolicy.runtime) public
@interface fruitname {
String value () default "";
First, a note typically requires 2 meta annotation modifiers:
@Target (Elementtype.field)
@Retention (Retentionpolicy.runtime)
Specific effects above have been explained.
All annotations will have a section similar to "Func". This can be interpreted as a parameter of the annotation.
Package com.joyfulmath.jvmexample.annnotaion;
Import Com.joyfulmath.jvmexample.TraceLog;
/**
* @author deman.lu
* @version on 2016-05-23 13:37
/public class Apple {
@FruitName ("Apple") C8/>string Applename;
public void Displayapplename ()
{
tracelog.i (applename);
}
}
Log of this code:
05-23 13:39:38.780 26792-26792/com.joyfulmath.jvmexample i/apple:displayapplename:null [at (Apple.java:16)]
No value was assigned to success, why? What exactly is the annotation "Apple" assigned to the filed, the compiler does not yet know how to do it.
3. Annotation processor
We also need a processor to explain how the annotation works, or it will be the same as the annotation.
By reflection, you can get the contents of the annotation:
Package com.joyfulmath.jvmexample.annnotaion;
Import Com.joyfulmath.jvmexample.TraceLog;
Import Java.lang.reflect.Field;
/**
* @author deman.lu
* @version on 2016-05-23 14:08/public
class Fruitinfoutils {public
static void Getfruitinfo (class<?> clazz)
{
String fruitnamestr = "";
field[] fields = Clazz.getdeclaredfields ();
for (Field field:fields)
{
if (field.isannotationpresent (fruitname.class))
{
Fruitname Fruitname = Field.getannotation (fruitname.class);
Fruitnamestr = Fruitname.value ();
TRACELOG.I (FRUITNAMESTR);}}}
This is the general usage of annotations.
Android Annotation Framework Parsing
As you can see from the above, the use of the annotation frame is essentially a reflection.
But if I use the annotation frame with the function of reflection, I might as well use it directly, but simply.
If there is a mechanism, you can avoid writing a lot of duplicate similar code, especially when Android development, a lot of Findviewbyid & onclick events corresponding.
The pattern of the code is consistent, but the code is different, this time, the use of the annotation framework can save a lot of development time, of course, the corresponding additional overhead.
Here's an example of using Butterknife:
@BindString (R.string.login_error)
String Loginerrormessage;
It seems very simple to assign a string to the initial value of an "." This can save some time. Of course, this is just an example,
If you use a lot of other annotations, you can save a significant portion of your development time.
Let's take a look at how it's going to happen:
Package butterknife;
Import Android.support.annotation.StringRes;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.Target;
Import static Java.lang.annotation.ElementType.FIELD;
Import static Java.lang.annotation.RetentionPolicy.CLASS;
/**
* Bind A field to the specified string resource ID.
* <pre><code>
* {@literal @}bindstring (r.string.username_error) string usernameerrortext;
* </code></pre>
/
@Retention (CLASS) @Target (FIELD) public
@interface bindstring {
/** String Resource ID to which the field would be bound. *
/@StringRes int value ();
}
Bindstring, there is only one parameter, value, that is, the assignment is @stringres.
Ditto, where the annotations are defined and used, but where the annotations are really interpreted are as follows: Butterknifeprocessor
Private Map<typeelement, bindingclass> findandparsetargets (roundenvironment env)
This function intercepts part of the code:
Process each @BindString element.
For (Element Element:env.getElementsAnnotatedWith (Bindstring.class)) {
if (!) Superficialvalidation.validateelement (Element)) continue;
try {
parseresourcestring (element, Targetclassmap, erasedtargetnames);
} catch (Exception e) {
Logparsingerror (element, Bindstring.class, E);
}
}
Locate the elements of all bindstring annotations, and then start the analysis:
private void Parseresourcestring (element element, map<typeelement, bindingclass> Targetclassmap, set<
Typeelement> erasedtargetnames) {Boolean haserror = false;
Typeelement enclosingelement = (typeelement) element.getenclosingelement ();
Verify that's the target type is String. if (! String_type.equals (Element.astype (). toString ()) {error (element, @%s field TYPE must be ' String ').
(%s.%s) ", BindString.class.getSimpleName (), Enclosingelement.getqualifiedname (), Element.getsimplename ());
Haserror = true;
}//Verify common generated code restrictions.
Haserror |= Isinaccessibleviageneratedcode (Bindstring.class, "fields", Element);
Haserror |= isbindinginwrongpackage (bindstring.class, Element);
if (haserror) {return;}//Assemble information on the field.
String name = Element.getsimplename (). toString ();
int id = element.getannotation (bindstring.class). Value ();
Bindingclass Bindingclass = Getorcreatetargetclass (Targetclassmap, enclosingelement); Fieldresourcebinding binding = new fieldresourcebinding (ID, name, "GetString", false);
Bindingclass.addresource (binding);
Erasedtargetnames.add (enclosingelement); }
First verify that the element is a string type.
Assemble information on the field.
String name = Element.getsimplename (). toString ();
Gets the name of the field and the string ID.
Eventually
Map<typeelement, bindingclass> Targetclassmap
Elements and annotations are described, and the map of the way one by one corresponds to storage.
@Override public Boolean process (SET< extends typeelement> elements, roundenvironment env) {
map< Typeelement, bindingclass> targetclassmap = findandparsetargets (env);
For (Map.entry<typeelement, bindingclass> entry:targetClassMap.entrySet ()) {
Typeelement typeelement = Entry.getkey ();
Bindingclass Bindingclass = Entry.getvalue ();
try {
Bindingclass.brewjava (). WriteTo (filer);
} catch (IOException e) {
error (typeelement, "unable to Write view binder for type%s:%s, typeelement,
e.getmessage ());
}
return true;
}
This is where the annotation frame starts, an independent process. Specific details of this article are not studied, just clear, here is the frame-driven place.
From the above information has been cleared, all the annotation information is stored in the Targetclassmap.
The red code above should be at the core of the annotation frame.
Since Java SE5 began, Java has introduced the APT tool, which can preprocess annotations, Java SE6, and support extended annotation processors,
and at compile time, we can use a custom annotation processor to generate new Java code at Java compile time, according to the rules.
Javafile Brewjava () {
Typespec.builder result = Typespec.classbuilder (generatedclassname)
. Addmodifiers ( public);
if (isfinal) {
result.addmodifiers (modifier.final);
} else {
result.addtypevariable ( Typevariablename.get ("T", Targettypename));
TypeName targettype = isfinal? TargetTypeName:TypeVariableName.get ("T");
if (hasparentbinding ()) {
Result.superclass (parameterizedtypename.get) (Parentbinding.generatedclassname, TargetType));
} else {
result.addsuperinterface (Parameterizedtypename.get (View_binder, TargetType));
}
Result.addmethod (Createbindmethod (TargetType));
if (Isgeneratingunbinder ()) {
Result.addtype (Createunbinderclass (TargetType));
} else if (!isfinal) {
Result.addmethod (Createbindtotargetmethod ());
}
Return Javafile.builder (Generatedclassname.packagename (), Result.build ())
. Addfilecomment ("Generated code From Butter knife. Do not modify! ")
. Build ();
}
The key to this passage is to create a new file.
The
then writes the relevant content.