The Java reflection mechanism provides a powerful application interface to help us detect and execute operations on objects at runtime. This mechanism allows programmers to examine an unknown object and obtain its attributes, such as methods on the object, attributes of JavaBean, and inheritance relationships.
Java has two types of values. One is the class type, which defines the object attributes in a class. Class type is a basic component of the object-oriented structure. The second type of value is the basic data type. The reflection type is usually used for the class type, but it can also be easily applied to the basic type of Java.
The basic types in Java inherit from C-based syntax, including boolean, byte, short, int, long, float, double, char, and other types.
Each basic type is associated with a java class. These classes are encapsulated in java. lang. package. This package imports all java source code files by default.
In java. in the basic data type packaging class of the lang Package, classes are not used as defined objects, but special constants are used to represent the type of basic data ). for example, it is a constant Interger. TYPE, instead of Integer, indicates the int TYPE, which is Byte. the TYPE constant indicates the byte TYPE. this method makes it possible to create a common component for an unknown JavaBean.
The following is an example piece. Its function is to set the value in the JavaBean according to a sent HttpServletRequest.
// Thrown
Exceptions are left out for reading of reading...
Object bean = ....
BeanInfo bi = Introspector. getBeanInfo (bean. getClass ());
PropertyDescriptor [] PPS = bi. getPropertyDescriptors ();
For (int I = 0; I
String name = PPS [I]. getName ();
String value = request. getParameter (name );
If (value! = Null ){
Method method = PPS [I]. getWriteMethod (
);
Value = convert (value,
Method. getParameterType () [0]);
Method. invoke (bean, new Object [
] {Value });
}
)
The Code missing in the Convert method is defined as follows:
Public Object
Convert (Object value, Class type ){
String name = type. getName ();
If ("java. lang. String. equals (name )){
Return value. toString ();
} Else
If ("java. lang. Long". equals (name) | (type =
Long. TYPE )){
Return convertToLong (value );
} Else
If ("java. lang. Integer". equals (name) | (type
= Integer. TYPE )){
Return convertToInteger (value );
} Else
.....
}