Java5 begins, Java begins to support metadata, i.e. annotation (annotations/tags)
Meta Data:Metadata: Data describing the data:
All annotation are sub-interfaces of the Java.lang.annotation.Annotation interface, so annotation is a special interface (enumeration is also a special class)
Enumerations: All enumerated types are subclasses of the Java.lang.Enum class. ---> Enumeration is a special kind of class.
Note: All annotations are sub-interfaces of the Java.lang.annotation.Annotation interface, and annotations are a special interface.
Use annotations:
Note: The annotation itself does not have any function, it must provide a third party program to give it function。
There are three-party programs involved in using annotations:
1. First, there must be a annotation class;
2, the second must be affixed to the program elements;
3, must have a third party program to give the annotation special function (reflection operation).
In Java, there are 5 annotations: (3 Java5, 1 Java7, Java8 1):
@Override qualify subclasses to overwrite the parent class method
@Deprecated tags are obsolete and obsolete methods/classes are not recommended for use
@SuppressWarings suppress a compiler warning, just suppress a warning, the problem persists
@SuppressWarings (value= "All")
@safeVarargs suppression heap pollution warning (Java7 started to appear)
@FunctionalInterface Java8 appears, representing a functional interface, allowing only one abstract method in the interface. If there is only one abstract method in an interface, you may not use annotations. You can use functional programming (lambda syntax).
Java5 began to appear annotations, only began to have @deprecated annotation, but Java.util.Date class in JDK1.1 time many methods are outdated:
Marking a method before Java5 is obsolete, using document annotations.
/**
* Created by Layne_yao on 2017-8-5 a.m. 9:51:42.
* Csdn:http://blog.csdn.net/jsagacity
/public class Annotationdemo {
//starting from Java5
@Deprecated
public void Annotation1 () {
}
//Before JAVA5
/**
* @deprecated/
public
void Annotation2 () { c13/>} public
static void Main (string[] args) {
}
}
Note:Used to attach to a class, method, constructor, field, parameter, etc. to give a certain function to the attached program element.
Meta Note:In the definition of annotations, you must use meta annotations to annotate the annotations of the meta annotations.
@Retention:Determines the period at which annotations can be maintained, for a total of three periods, all encapsulated in the Retentionpolicy enumeration class:
SOURCE:The annotation is discarded at compile time, does not exist in the bytecode file, only exists in the source file;
CLASS:The annotation can exist in both the source file and the bytecode file, but is lost once it is loaded into the JVM;
RUNTIME:The annotation can exist in the source file, in bytecode, in the JVM.
Custom annotation classes are runtime, because we need to give annotations special functionality through reflection during runtime.
@Target: Determines which member elements the annotation can be attached to. There are many member elements that can be pasted, all encapsulated in the ElementType enumeration class.
Elementtype.annotation_type can only modify annotation type declarations
Elementtype.constructor can only modify the construction method declaration
Elementtype.field can only modify field declarations (including enumerated constants)
Elementtype.local_variable can only modify local variable declarations
Elementtype.method can only modify method declarations
Elementtype.package can only modify package declarations
Elementtype.parameter can only modify parameter declarations
Elementtype.type can only modify classes, interfaces (including annotation types) or enumeration declarations
@Documentd: Labels with @documentd annotations are saved in the Word API document.
@Inherited: @Inherited labeled labels can be inherited by the quilt class.
A method of obtaining/judging annotations in Class,method,field,constructor
Common APIs:
Annotation getannotation (class Annotationclass): Determines whether the current class, method, field has the specified annotation, and if so, returns the current object, if NULL is not returned;
Annotation[] Getannotations (): Returns all annotations that exist on this element.
Boolean isannotationpresent (Class Annotationclass): Returns True if an annotation of the specified type exists on this element, or false.
Annotation class:
Define note
@Target (elementtype.type)//Can only modify classes, interfaces (including annotation types) or enumeration declarations
@Retention (retentionpolicy.runtime)// The annotation can exist in the source file, in bytecode, in the JVM. Public
@interface INFO {
//annotation is a special interface with an abstract method in the interface, which is called Attribute
String username () in the annotation eight abstract method.
the int age () default 20;//default is set to the defaults
string[] Hobby ();
Gender sex () default gender.none;
}
Gender need to be set to public:
/**
* Created by Layne_yao on 2017-8-5 a.m. 11:11:03.
* csdn:http://blog.csdn.net/jsagacity
*
/public enum gender{
Boy,girl,none
}
To give a special function to a class:
/** * Created by Layne_yao on 2017-8-5 9:51:42. * Csdn:http://blog.csdn.net/jsagacity//The pasted program element @INFO (username = "Layne", age =, sex = gender.boy, hobby = {"Java" , "Android", "C + +}" class User {@Deprecated public void DoWork () {}}//give annotations special functionality to public class Annotationdemo
1 {public static void main (string[] args) throws Exception {//Get the information class CLS = User.class in the VIP annotation on the person class;
Gets all annotations on the person class annotation[] as = Cls.getannotations ();
Determine if there is a VIP annotation on the person class Boolean ispresent = Cls.isannotationpresent (Info.class);
if (ispresent) {//Remove the annotation on the person class Annotation A = Cls.getannotation (Info.class);
Get the attribute value in the VIP annotation (call the abstract method of VIP) Info VIP = (info) A;
System.out.println (Vip.username ());
System.out.println (Vip.age ());
System.out.println (Vip.sex ());
//requirements: Get the deprecated annotation on the DoWork method//1: Get the Byte code file class Doworkcls = User.class of the classes where the DoWork method is located;
2: Get the Method object of DoWork methods m = Doworkcls.getmethod ("DoWork");
System.out.println (m); 3: Get the annotations on the current method deprecated Depre = m.getannotation (Deprecated.class);
System.out.println (Depre); }
}
Run Result:
The above program does not give annotation functionality.
Next, create a new Android project with two controls added to the layout file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools= "http:// Schemas.android.com/tools "
android:layout_width=" match_parent "
android:layout_height=" Match_parent "
tools:context= "com.example.annomationdemo.MainActivity" >
<textview
android:id= "@+id/tv_show "
android:layout_width=" wrap_content "
android:layout_height=" wrap_content "
android:layout_ Alignparenttop= "true"
android:layout_centerhorizontal= "true"
android:layout_margintop= "180DP"
android:text= "@string/hello_world"/>
<button
android:id= "@+id/bt_show"
android:layout_ Width= "Wrap_content"
android:layout_height= "wrap_content"
android:layout_centerhorizontal= "true"
android:layout_centervertical= "true"
android:text= "button"/>
</RelativeLayout>
Create a new annotation class:
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Target ({Elementtype.field})
@Retention (retentionpolicy.runtime) public
@interface getviewto {
int Value () default -1;
}
In Mainactivity.java:
public class Mainactivity extends Actionbaractivity {@getViewTo (r.id.tv_show) private TextView tv_show;
@getViewTo (r.id.bt_show) private Button bt_show;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Create View Getallannomationview () through annotations; Bt_show.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {tv_show.settext ("
Annotations to obtain success ");
}
}); /** * Parse annotations, get control/private void Getallannomationview () {//Get member variable field[] fields = This.getclass (). g
Etdeclaredfields (); for (Field field:fields) {try {///judge whether the annotation is an empty if (Field.getannotations ()!=null) {//Determine the annotation type if (Field.isa
Nnotationpresent (Getviewto.class)) {//Allow modification of reflection properties Field.setaccessible (True);
Getviewto getviewto = field.getannotation (Getviewto.class); By Findviewbyid the ID of the annotation, find VIEW and injected into the member variable Field.set (this, Findviewbyid (Getviewto.value ()));
A catch (Illegalaccessexception e) {e.printstacktrace ());
catch (IllegalArgumentException e) {e.printstacktrace (); }
}
}
}
This does not demonstrate the results of the operation, you may feel a bit like butterknife after the run, but Butterknife is much stronger than this.