The Java reflection mechanism provides a powerful application interface to help us detect and execute operations on objects at run time. This mechanism allows the programmer to examine an unknown object and obtain its properties, such as the method on the object, the attributes of the JavaBean, and the inheritance relationship.
There are two types of values in Java, one is the class type, which defines the object's properties in a class. A class type is an essential component of an object-oriented structure. The second type of value is the base data type. Reflection types are typically used for class types, but they can also be easily applied to basic types of java.
The basic types in Java inherit from the syntax based on C, which includes the types Boolean, Byte, short, int, long, float, double, char, and so on.
Each of the basic types is associated with a Java class. These classes are encapsulated in Java.lang.package, and this package imports all Java source code files by default.
In the Java.lang package's basic data type wrapper class, instead of using classes (Class) in the same way as defining objects, you use special Changshilai to represent the type (type) of the underlying data. For example, a constant interger.type instead of a class integer represents an int type. Is the Byte.type constant that represents the byte type. This approach makes it possible to create generic components for an unknown JavaBean.
The following is an example fragment whose function is to set the value in JavaBean from a httpservletrequest.
//Thrown
Exceptions are left to ease of reading ...
Object bean = ....
BeanInfo bi = introspector.getbeaninfo (Bean.getclass ());
propertydescriptor[] pds = Bi.getpropertydescriptors ();
for (int i=0; I String name = Pds[i].getname ();
String value = request.getparameter (name);
if (value!= null) {
Method method = Pds[i].getwritemethod (
);
value = Convert (value,
Method.getparame Tertype () [0]);
Method.invoke (Bean, new object[
] {value});
} The missing code 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
...
}