Basic Attributes and advanced attributes of inner province, JavaBean, propertydescriptor, introspector, beanutils toolkit, annotation, ention, target, and Annotation

Source: Internet
Author: User

This article Reprinted from: http://blog.sina.com.cn/s/blog_5d65a16901011kom.html

Keywords: inner province, JavaBean, propertydescriptor, introspector, beanutils toolkit, annotation, ention, target, basic attributes and advanced attributes of Annotation

Introspector

Javabean is mainly used to transmit data information. Its method is used to access private variables and the method name complies with certain rules.

If information is transmitted between two modules, the information can be encapsulated into a JavaBean object called a value object or VO ". There are few methods. The information is stored in the private variables of the class and obtained through set () and get.

Inner province is mainly used to operate JavaBean. The internal methods of JavaBean should follow certain rules, such as void setage (INT age) and INT getage (). JavaBean can be used as a common class. If a common class contains the Set () and get () methods, it can also be used as a JavaBean.

The attributes of JavaBean are inferred through the get () and set () methods, that is, the letters after get and set are removed. For example, if the attribute is age, rather than a member variable, because the member variables are invisible.

Rules for obtaining attribute names: If the second letter of the attribute name is in lower case, the first letter is in lower case. For example, gettime-> time, settime-> time, getcpu-> CPU.

Benefits of processing JavaBean:

1. Java EE needs to be used in many places.

2. the API that JDK provides to Javabean is called introspection.

 

Propertydescriptor class

Propertydescriptor class RepresentationJavaBeanClass exports an attribute through memory. Main Methods:

1. getpropertytype () to obtain the Class Object of the attribute.

2. getreadmethod () is used to obtain the method used to read the attribute value. getwritemethod () is used to obtain the method used to write the attribute value.

3. Obtain the hash value of an object using hashcode.

4. setreadmethod (method readmethod): Set the method used to read the attribute value; setwritemethod (methodwritemethod): Set the method used to write the attribute value;

Export package java. Bean .*;

Get the corresponding value through the attribute name and use the reflection method as follows:

Reflectpoint pt1 = new reflectpoint (7,9 );
String propertyname = "X"; // get a value for an attribute.
Propertydescriptor Pd = new propertydescriptor (propertyname, pt1.getclass ());
Method methodgetx = Pd. getreadmethod (); // read the get () method
Object revalue = methodgetx. Invoke (pt1 );

 

Set a value for an attribute as follows:

String propertyname2 = "Y"; // set the value for an attribute.
Propertydescriptor Pd2 = new propertydescriptor (propertyname2, pt1.getclass ());
Method methodsety = pd2.getwritemethod (); // write the Set () method
Methodsety. Invoke (pt1, 3 );

 

Right-click "Source-" generate geters and setters, and create the get () and set () methods.

Select some code, right-click-refactor-extract method, and create a method to improve reusability.

 

Introspector class

Encapsulate the attributes in JavaBean for operations. When the program regards a class as a JavaBean, it calls the introspector. getbeaninfo () method,ObtainedBeaninfoThe object encapsulates this class as a JavaBeanThe result information, that is, the attribute information.. You need to export the java. Beans. * package .*.

Getpropertydescriptors () to obtain the attribute description. You can use the beaninfo Traversal method to find and set the class attributes.

private static Object getProperty_2(Object pt1, String propertyName) throws Exception 
{  
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass()); 
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();  
Object reValue = null; 
  for(PropertyDescriptor pd : pds)  
{    
if(pd.getName().equals(propertyName))    
{    
Method methodGetX = pd.getReadMethod();
reValue = methodGetX.invoke(pt1);
break;
}
}

 

ReturnRevalue;

}

Through the comparison between the two classes, we can see that both the propertydescriptor needs to be obtained, but in different ways: the former is obtained directly by creating an object, and the latter needs to be traversed, so it is more convenient to use the propertydescriptor class.

 

Beanutils Toolkit

Provides more and more convenient functions for JavaBean.

Beanutils. jar = beanutils-core.jar + beanutils-bean-collections.jar, you can add an additional jar package through buildpath, or create a lib directory under the project, copy the jar package in, And then load the jar package: right-click "add to buildpath. Export package: org. Apache. commons. beanutils. beanutils.

Use the log package provided by acpche together:Logging.

Obtain the attribute value, for example, beanutils.Getproperty(Pt1, "x"), returns a string

Set the attribute value, for example, beanutils.Setproperty(Pt1, "Y", 22). The parameter is automatically packaged as a string or basic type. Set the attribute value to a string. The obtained value is also a string, not a basic type.

Beanutils features:

1. Operations on attributes of the basic data type: During web development and use, the value is converted to a string during input and display, but the underlying operation uses the basic type.Type to actionAutomatically completed by beanutils.

2. operations on the attribute of the referenced data type:The class must have an object. It cannot beNull, For example,PrivateDate Birthday =NewDate ();.Operate on the attributes of the object rather than the entire objectFor example, beanutils.Setproperty(Pt1, "birthday. Time", 121 );

New Features of Java 7:MapAnd JavaBeanCan be converted to each other.Key is an attribute and value is a value.

Describe: JavaBean-> map; populate: Map-> JavaBean. For example:

Map map = (Name: Kim, age: 18 );

Beanutils. setproperty (MAP, "name", "Kim ");

Copyproperties(Object DEST, objectorig) to copy the attribute values of an object to the attributes of another object. Ensure that the attributes are consistent.

 

Propertyutils class

Unlike beanutils, when you run the getproperty and setproperty operations,No type conversionUse the original type or packaging class of the property.

 

Annotation

Jdk1.5 introduces new features. In the java. Lang. annotation package.

For obsolete statements, Java prompts that the statements are outdated. The prompt is canceled in DOS through @ suppresswarnings ("deprecation"), but eclipse cannot be canceled. This is the annotation, which is equivalent to a tag.Compilers, development tools,JavacObtain the content in the annotation through reflection, and then identify what should be done and what should not be done. Annotations can be added to packages, classes, attributes, methods, parameters, and local variables.

An annotation is a class.@ Suppresswarnings, Cancel warning.@ Deprecated, ExpiredThe old version is available, and the new version is unavailable.

In a hashset set, the object must overwrite the equals () method of the object class. Otherwise, the equals () method of the object class will be used for comparison. The comparison method is incorrect. Override the equals () method, and the parameters must be consistent. To prevent errors from being written to objects of this class, add@ Override, Must overwrite the parent class method correctly, Instead of creating a new method.

 

Annotation Application

In the source program, call a class, which will use annotations. You need to prepare the annotation class first, and the class is calling the object of the annotation class. The annotation class is written like an interface, @ interface. First write the annotation class A, and place the annotation in Class B. Class C obtains the content of annotation class A through reflection when class B is called, and then clarifies what to do and what not to do. You can add multiple annotations.Annotation class Object: @ Interfacea.

The main () method must be placed under a class, but it is not necessarily related to this class.

Add annotation B in annotation class A, this annotation B is only for this annotation class a service, B is called "meta annotation ". Metadata and metadata are similar. There are two meta Annotations: ention and target. The annotation of the annotation class can be understood as the attribute of the annotation class.

 

 

Ention annotation class

Annotation lifecycle: the bytecode in the memory of the Java source File> class file. During compilation or running, annotations may be canceled.Encryption ention3Value means the stage at which the annotation is retained, Entionpolicy. Source, entionpolicy. Class (default), and entionpolicy. runtime.

@ Override and @ suppresswarnings are retained to the source stage by default; @ deprecated is retained to the runtime stage.

Annotation ention is equivalent to an attribute of the annotation class. Because the value of annotation ention is different, the annotation class is retained to different stages. The value of the internal encryption ention in the annotation class is represented by value. For example, in @ deprecated, value = runtime.

Encryption entionThe value is the enumerated entionpolicy.ValueThere are only three: source, class, and runtime.

 

Target annotation class

The property is the same as that of the annotation class,Position of the annotation classWhich is valid for that piece of data. For example, @ target (elementtype.Method)

TargetUse enumeration elementtype for Internal ValuesIndicatesThe main locations are: Annotations, constructor, attributes, local variables, functions, packages, parameters, and classes (default value ). Use arrays at multiple locations, for example, @ target ({elementtype.Method, Elementtype.Type}).

Class, interface, enumeration, annotation this kind of thing is represented by type, class parent class, jdk1.5 new features.

 

Basic Attributes of annotations

Attribute to provide more detailed information for the annotation.

Annotation is equivalent to interface, and attribute is equivalent to Method. For example, @ itcastannotation (color = "black") assigns a value to the attribute. The value is similar to the call method, for example, system.Out. Println (annotation. color ());.All attributes must appear unless there are default values.

If only the value attribute exists and there are no other attributes, you can ignore = and only target the value. For example, @ suppresswarnings ("deprecation "). Or there are other attributes and default values, for example, string color ()Default"Blue"; in this case, the value is displayed separately. Do not use =.

Obtains the attribute value of the annotation, for example

If(Annotationdemo.Class. Isannotationpresent (itcastannotation.Class)){

Itcastannotation annotation =

(Itcastannotation) annotationdemo.Class. Getannotation (itcastannotation.Class);

System.Out. Println (annotation. color ());

}

}

Use reflection to obtain the annotation object, and then let the object call the method corresponding to the attribute. Pay attention to type conversion.

Encryption ention and target are also attributes and are values corresponding to values. The value types are entionpolicy and elementtype, for example, @ retention (value = retentionpolicy.Runtime).

 

Advanced attributes of annotations

Add advanced attributes, arrays, enumeration, and annotations to annotations.

Attribute of array type

For example,Int[] Arr ()Default{3, 7, 5};, myannotation (ARR = {3, 7, 6 }). If the array has only one element, you can not add {}. @ Target ({elementtype.Method, Elementtype.Type}) Is also an attribute of the array type.

Enumeration type attributes

// Content inside the annotation class

Enumerationdemo. trafficlamp lamp ()DefaultEnumerationdemo. trafficlamp.Red;

// Call the annotation class

@ Itcastannotation (lamp = enumerationdemo. trafficlamp.Yellow)

// Perform operations on Annotations

System.Out. Println (annotation. Lamp (). nextlamp (). Name ());

Annotation type attributes

Add an annotation class as an attribute to another annotation class.

Metaannotation annotationatt ()Default@ Metaannotation ("Jobs ")

@ Itcastannotation (annotationatt = @ metaannotation ("Kim "))

Annotation. annotationatt (). Value ()

The Return Value of the annotation can be 8 basic types, String, class, enumeration, and arrays of the previous type, with internal attributes.

You need to learn the annotations in detail. You can use the Java language specification, that is, languagespecification.

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.