Implement annotation-based property injection through inheritance
To inject attributes with annotations, you must first define an annotation. The annotation is defined as follows:
Package everyworkdayprogramming. _ 2015_000023; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. inherited; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/* Four meta annotations, their meaning (personal memory) in turn, the object that generates documents that can be used by the quilt class and can be annotated during runtime is FIELD */@ incluented @ Inherited @ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. FIELD) public @ interface MyAnnotion {// There is a VALUE named value. The default VALUE is 123 String value () default "123 ";}
Package everyworkdayprogramming. _ 2015_000023; import java. lang. reflect. field; public class SuperClass {// perform attribute injection in the default constructor of our parent class, here, the subclass will call the property of the non-argument constructor of the parent class by default. public SuperClass () {// obtain all attribute fields in the class [] fields = this. getClass (). getDeclaredFields (); // traverse fieldsfor (Field field: fields) {// if this field has annotation MyAnnotionif (Field. isAnnotationPresent (MyAnnotion. class) {// obtain the corresponding MyAnnotion instance MyAnnotion myAnnotion = field. getAnnotation (MyAnnotion. class); try {// because field is a private attribute, set field here. setAccessible (true); // modify the field value to the field injected in annotion. set (this, myAnnotion. value ();} catch (IllegalArgumentException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();}}}}}
Package everyworkdayprogramming. _ 2015_000023;/* SubClass directly inherits our parent class */public class SubClass extends SuperClass {// call the annotation injection attribute. The default value is 123, set it to test @ MyAnnotion (value = "test") private String num; public String getNum () {return num;} public void setNum (String num) {this. num = num;} public static void main (String [] args) {// output our attribute value System. out. println (new SubClass (). getNum ());}}