Java gets the properties of an unknown type object

Source: Internet
Author: User

There are usually two ways to get properties of an unknown type object:

One is to obtain the value of the property by obtaining the annotated property by customizing the annotations, which is also an important implementation of spring parameter injection.

The second is to get the name of the property by reflection, and obtain the property by the property name, which is easy and easy to implement in the development.

I. About annotations 1, custom annotations

First, define a @interface type annotation interface

@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  Classbeanid {
}

The role of meta annotations is to be responsible for annotating other annotations.
[Email protected],
[Email protected],
[Email protected],
[email protected] These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the function of each meta-annotation and the instructions for using the corresponding sub-parameters.

The


    @Target illustrates the range of objects that are modified by annotation: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), method parameters, and local variables such as loop variables, catch parameters. Target can be more clearly decorated by using target in the declaration of the annotation type.
    function: Used to describe the use of annotations (that is, where the annotations described can be used)
    values (elementtype) are:
     1.CONSTRUCTOR: Used to describe the constructor
    2.FIELD: Used to describe the domain
    3.local_variable: Used to describe local variables
    4.METHOD: For description method
    5.PACKAGE: For description package
    6.PARAMETER: Used to describe parameters
    7.TYPE: For describing classes, interfaces (including annotation types) or enum declarations

@Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.
Function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the annotation being described is valid)
The values (Retentionpoicy) are:
1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)
Note: The Retentionpolicy property value of the annotation is rutime, so that the annotation processor can get the property value of the annotation by reflection, thus doing some logic processing of the runtime

How to set the parameters of the annotation type:
First, it can only be decorated with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string,enum,class,annotations data types, As well as these types of arrays. For example, String value (), where the parameter member is string;
Third, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses.

For example:

Example 1:

To customize an annotation:

@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  Classbeanid {    publicintdefault -1;}

Use this annotation:

 Public classClassbean {@ClassBeanId (id= 20)//the default value for using defined annotations is 20. If you need to assign a value, you need to use reflection to remove the value of the ID and assign it to the ID of the current class    Private intID;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; } @Override PublicString toString () {return"Classbean [id=" + ID + "]"; }    }

Definition gets the property under the annotation

 Public Static<T>voidGetData (T data)throwsIllegalArgumentException, illegalaccessexception{        intID = 0; Class Clazz=Data.getclass (); Field[] Fields=Clazz.getdeclaredfields ();  for(Field field:fields) {if(Field.getannotation (Classbeanid.class) !=NULL) {field.setaccessible (true); ID=field.getint (data);} System.out.println ("ID:" +ID); }    }

Gets the object's ID property by passing it in to the method, judging whether the object property has annotations added by reflection.

To implement parameter injection in a similar spring framework, you need to redefine a set of methods to pass the parameters in the annotations to the object, as follows:

 Public Static<T>voidGetdatafromannotation (T data)throwsIllegalArgumentException, illegalaccessexception{        intID = 0; Class Clazz=Data.getclass (); Field[] Fields=Clazz.getdeclaredfields ();  for(Field field:fields) {if(Field.getannotation (Classbeanid.class) !=NULL){//determines whether the property is annotatedField.setaccessible (true); Classbeanid Classbeanid= Field.getannotation (Classbeanid.class);//instance of the annotationField.setint (data, classbeanid.id ());//gets the value of the annotation and assigns the value to the incoming object            }        }    }

Although not a strict implementation mechanism of the spring framework, the principle is the same.

second, about reflection

The

Gets the name of the property by reflection and compares the property name to get some property values in an unknown type object. This is a more common practice.

 public  static  <T> void  Getdatafield (T data) throws   = Data.getclass (        );        field[] Fields  = Clazz.getdeclaredfields ();  for   (Field field:fields) {String nam            E  = Field.getname ();  if  (name.equals ("id"  true  );            Field.setint (data,  29); }        }    }

Java gets the properties of an unknown type object

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.