[Post] reflection, the soul of Java

Source: Internet
Author: User
Reflection enables your program code to access the internal information of classes loaded into the JVM, allowing you to write and execute code that is not selected in the source code for collaboration. This makes reflection a major tool for building flexible applications. However, it should be noted that, if improperly used, reflection costs are high. In Part 1 of the Java platform series, software consultant Dennis sosnoski introduced how to use reflection and some related costs. You will also find out how Java reflection API enables you to associate objects at runtime.

In "Java programming dynamics, part 1," I introduced you to Java programming classes and class loading. This article introduces some information about the Java binary format. This month I will explain how to use the Java reflection API to access and use the same information at runtime. To keep the developers familiar with reflection basics interested in this article, I will introduce how reflection performance is compared with direct access.

Using Reflection is different from conventional Java programming, where it cooperates with metadata-data describing other data. The special types of original data accessed by Java reflection are descriptions of classes and objects in JVM. Reflection allows you to access a wide range of class information at runtime. It even enables you to read and write fields and call methods of the class selected during runtime.

Reflection is a powerful tool. It allows you to create flexible code that can be configured during running without the need for source representative links between components. However, there are some questions about some aspects of reflection. In this article, I will discuss in depth why you may not want to use reflection in your program and why you should do so. After understanding the balance analysis, you can decide whether the advantage is greater than the disadvantage.

Beginner's class
The start point of reflection is always a java. Lang. class instance. If you want to collaborate with a predefined class, Java provides a convenient and convenient way to directly obtain the class instance:

Part 2: "loading classes and classes"

Code:
Class CLAS = myclass. Class;


When you use this technology, all the work involved in the loading class is performed behind the scenes. However, this method is not suitable if you need to read class names from some external sources at runtime. In fact, you need to use a class loader to find the class information. One of the following methods is described:

Code:
// "Name" is the class name to load
Class CLAS = NULL;
Try {
Clas = Class. forname (name );
} Catch (classnotfoundexception ex ){
// Handle exception case
}
// Use the loaded class


If the class has been loaded, you will get the existing class information. If the class is not loaded, the Class Loader loads the class and returns the newly created class instance.

Class-based reflection
The Class Object provides you with all the basic hooks for accessing the reflection of class metadata. This type of metadata includes information about the class itself, such as the parent class of the package and class, and the interfaces implemented by this class. It also includes the detailed information of the constructor, field, and method defined by this class. These final projects are the most frequently used projects in programming, so I will provide some examples of collaboration with them later in this section.

Java. Lang. class provides four independent reflection calls for any of the following three components: constructor, field, and method to obtain information in different ways. All calls follow a standard format. The following is a set of reflection calls used to find constructors:
Constructor getconstructor (class [] Params) -- obtains a common constructor that uses special parameter types,

Constructor [] getconstructors () -- obtain all public constructors of the class

Constructor getdeclaredconstructor (class [] Params) -- obtains constructors using specific parameter types (not related to the access level)

Constructor [] getdeclaredconstructors () -- obtain all constructors of the class (irrelevant to the access level)

Each type of these calls returns one or more java. Lang. Reflect. constructor functions. This constructor class defines the newinstance method. It uses a group of objects as its unique parameters and then returns the newly created original class instance. This group of objects is the parameter value used to construct function calls. As an example to explain this workflow, assume that you have a twostring class and a constrfunction that uses a pair of strings, as shown in Listing 1:
Listing 1: classes created from a pair of strings

Code:
Public class twostring {
Private string m_s1, m_s2;
Public twostring (string S1, string S2 ){
M_s1 = S1;
M_s2 = S2;
}
}


The code in Listing 2 gets the constructor and uses it to create an instance of the twostring class using strings "A" and "B:
List 2: Reflection call of Constructor

Code:

Class [] types = new class [] {string. Class, String. Class };
Constructor cons = twostring. Class. getconstructor (types );
Object [] ARGs = new object [] {"A", "B "};
Twostring Ts = cons. newinstance (ARGs );


The code in Listing 2 ignores multiple possible exception types thrown by different reflection methods. Exceptions are detailed in the javadoc API description, so for the sake of conciseness, I will ignore them in all program instances.

Although I am discussing the constructor topic, the Java programming language also defines a special shortcut that you can use to create an instance of a class using a non-parameter (or default) constructor. This shortcut is embedded into the class definition as follows:
Object newinstance () -- use the default function to create a new instance

Even if this method only allows you to use a special constructor, it provides a convenient shortcut if it is exactly what you need. This technique is particularly useful when collaborating with JavaBeans. JavaBeans need to define common and non-parameter constructors.

The class reflection call that adds a field to obtain the field information is different from the call that is used to access the constructor. The field name is used in the parameter type array:
Field getfield (string name) -- Obtain the named public field

Field [] getfields () -- obtain all public fields of the class

Field getdeclaredfield (string name) -- Obtain the name field of the class declaration

Field [] getdeclaredfields () -- get all fields declared by class

Although similar to the constructor call, there is still an important difference in fields: the first two variables return information about public fields that can be accessed through the class-even if they come from the ancestor class. The last two variables return the information of fields directly declared by the class, regardless of the access type of the field.

Call the returned java. Lang. Reflect. Field instance to define the getxxx and setxxx methods of all primary types, as well as common get and set methods for collaboration with object references. You can select an appropriate method based on the actual field type, and the getxxx method will automatically process the extended conversion (for example, using the getint method to retrieve a byte value ).

Listing 3 shows an instance using the field reflection method. The Int field of the object is added according to the name in the method format:
Listing 3: adding a field through reflection

Code:
Public int incrementfield (string name, object OBJ) throws ...{
Field field = obj. getclass (). getdeclaredfield (name );
Int value = field. getint (OBJ) + 1;
Field. setint (OBJ, value );
Return value;
}


This method begins to show some flexibility of reflection. Different from the specific class collaboration, incrementfield uses the getclass method of the passed object to find the class information, and then directly searches for the named field in the class.

Increase by reflection
The class reflection call for obtaining method information is similar to the call for constructors and fields:
Method getmethod (string name, class [] Params) -- use a specific parameter type to obtain the named public Method

Method [] getmethods () -- obtain all public methods of the class

Method getdeclaredmethod (string name, class [] Params) -- Obtain the class declaration naming method by using the parameter type of the close-up.

Method [] getdeclaredmethods () -- obtain all methods declared by class

Like a field call, the first two variables return information about the public methods that can be accessed through the class, even if they are from the ancestor class. The last two variables return the information of the method declared by the class, regardless of the access type of the method.

Call the returned java. Lang. Reflect. Method Instance to define an invoke method, which can be used to call a method on an instance of the class being defined. This invoke method uses two parameters to provide an array of class instances and parameter values for calls.

Listing 4 further describes the field instance and shows an instance that reflects the running method. This method adds an int JavaBean attribute that defines the get and set methods. For example, if the object defines the getcount and setcount methods for an integer Count value, you can pass "count" as the name parameter to this method in one call to increase the value.
Listing 4: adding a JavaBean attribute through reflection

Code:
Public int incrementproperty (string name, object OBJ ){
String prop = character. touppercase (name. charat (0) +
Name. substring (1 );
String mname = "get" + Prop;
Class [] types = new class [] {};
Method method = obj. getclass (). getmethod (mname, types );
Object result = method. Invoke (OBJ, new object [0]);
Int value = (integer) result). intvalue () + 1;
Mname = "set" + Prop;
Types = new class [] {Int. Class };
Method = obj. getclass (). getmethod (mname, types );
Method. Invoke (OBJ, new object [] {New INTEGER (value )});
Return value;
}


In order to follow the JavaBeans convention, I changed the first letter of the attribute name to uppercase. Then, I considered get to create a read method name and set to create a write method name. The JavaBeans read method only returns the value, while the write method uses the value as the unique parameter. Therefore, I specify the parameter type of the method for matching. Finally, this Convention requires the method to be public, so I use the search format to find the public methods that can be called in the class.

This instance is the first instance that I use reflection to pass the main value, so now let's see how it works. The basic principle is very simple: No matter when you need to pass the main value, you only need to replace the main value with an instance of the corresponding encapsulation class (defined in the Java. lang Package. This can be applied to call and return. Therefore, when I call the get method in an instance, I expect the result to be the java. Lang. Integer encapsulation of the actual int attribute value.

Reflection Array
An array is an object in the Java programming language. Like all objects, they all have classes. If you have an array and use the standard getclass method, you can obtain the class of this array, just like any other object. However, you do not use an existing instance to obtain objects of different classes than other types. Even if you have an array class, you cannot directly perform too many operations on it. Reflection provides constructor access for standard classes and cannot be used for arrays. arrays do not have any accessible fields, only basic java. lang. object method definition is used for array objects.

Special Handling of arrays uses a set of static methods provided by the java. Lang. Reflect. array class. The method in this class allows you to create a new array, get the length of the array object, read and write the index value of the array object.

Listing 5 shows an effective method to resize an existing array. It uses reflection to create new arrays of the same type, and then copies all data in the old array before returning the new array.
Listing 5: extending an array through reflection

Code:
Public object growarray (Object array, int size ){
Class type = array. getclass (). getcomponenttype ();
Object grown = array. newinstance (type, size );
System. arraycopy (array, 0, grown, 0,
Math. Min (array. getlength (array), size ));
Return grown;
}


Security and reflection
Security is a complicated issue when dealing with reflection. Reflection is often used by framework-type code. Because of this, you may want the framework to fully access your code without the need to consider regular access restrictions. However, in other cases, uncontrolled access brings serious security risks, such as running code in an untrusted code sharing environment.

Due to these conflicting requirements, the Java programming language defines a multi-level method to handle reflection security. The basic mode is to impose the same limitations on reflection as source code access:
Access from any location to public components
The class itself has no access to private components.
Limited access to protected and packaged (default access) components

But-at least some time there is a simple way around these limitations. The constructor, field, and method classes I used in the previous instance all extend a common basic class-java. Lang. Reflect. accessibleobject class. This class defines a setaccessible method that enables you to start or disable access detection for one of these classes. The only problem is that if the security manager is used, it will detect whether the code that is disabling access detection permits this. If not, the security manager throws an exception.

Listing 6 shows a program. Reflection is used on an instance of the twostring class in Listing 1 to show that security is running:
Listing 6: Reflection Security running

Code:

Public class reflectsecurity {
Public static void main (string [] ARGs ){
Try {
Twostring Ts = new twostring ("A", "B ");
Field field = Clas. getdeclaredfield ("m_s1 ");
// Field. setaccessible (true );
System. Out. println ("retrieved value is" +
Field. Get (insT ));
} Catch (exception ex ){
Ex. printstacktrace (system. Out );
}
}
}


If you compile this program and run it directly from the command line without using any specific parameters, it will throw an illegalaccessexception in the field. Get (insT) Call. If you do not comment on the field. setaccessible (true) line of code, recompile and re-run the code, and it will succeed. Finally, if you add the JVM parameter-djava. Security. Manager in the command line to implement the security manager, it will fail again unless you have defined the permission for the reflectsecurity class.

Reflection Performance
Reflection is a powerful tool, but there are also some shortcomings. A major drawback is the impact on performance. Reflection is basically an interpreted operation. You can tell JVM what you want to do and what it meets your requirements. This type of operation is always slower than simply performing the same operation. In order to explain the performance cost of using reflection, I have prepared a set of benchmark programs for this article (see references for the complete code link ).

Listing 7 is an excerpt from the field access performance test, including the basic test method. One form of test field access for each method -- accesssame works with member fields of the same object, and accessother uses fields of another object that can be directly accessed, accessreflection uses fields of another object that can be accessed through reflection. In each case, the method executes the same computation-a simple addition/Multiplication sequence in a loop.
Listing 7: field access performance test code

Code:

Public int accesssame (INT loops ){
M_value = 0;
For (INT Index = 0; index <loops; index ++ ){
M_value = (m_value + additive_value )*
Multiplier_value;
}
Return m_value;
}

Public int accessreference (INT loops ){
Timingclass timing = new timingclass ();
For (INT Index = 0; index <loops; index ++ ){
Timing. m_value = (timing. m_value + additive_value )*
Multiplier_value;
}
Return timing. m_value;
}

Public int accessreflection (INT loops) throws exception {
Timingclass timing = new timingclass ();
Try {
Field field = timingclass. Class.
Getdeclaredfield ("m_value ");
For (INT Index = 0; index <loops; index ++ ){
Int value = (field. getint (timing) +
Additive_value) * multiplier_value;
Field. setint (timing, value );
}
Return timing. m_value;
} Catch (exception ex ){
System. Out. println ("Error Using Reflection ");
Throw ex;
}
}


The test program repeatedly calls each method and uses a large number of cycles to measure the average time of multiple calls. The average value does not include the first call time of each method. Therefore, the initialization time is not a factor in the result. In the test conducted for this article, each call uses 10 million cycles and runs on a 1 GHz piiim system. The timing result of the three different Linux JVMs is shown in 1. All tests use the default settings for each JVM.

The log scale in the Table above can display all the time, but reduces the visible impact of the difference. In the first two figures (Sun JVM), the reflection execution time exceeds 1000 times of the direct access time. By comparison, ibm jvm may be a little better, but the reflection method still needs to be more than 700 times longer than other methods. There is no significant difference in time between the other two methods on any JVM, but ibm jvm is almost twice faster than Sun JVM. Most likely, this difference reflects the professional Optimization of sun hot spot JVM, which performs poorly in simple benchmarking.

In addition to the field access time test, I also tested the same method call time. In method calls, I tried three access variables that are the same as field access, and added the use of non-parametric method variables instead of passing and returning a value in method calls. Listing 8 shows the code used to test the form of call passing and return values.
Listing 8: Method access performance test code

Code:

Public int calldirectargs (INT loops ){
Int value = 0;
For (INT Index = 0; index <loops; index ++ ){
Value = step (value );
}
Return value;
}

Public int callreferenceargs (INT loops ){
Timingclass timing = new timingclass ();
Int value = 0;
For (INT Index = 0; index <loops; index ++ ){
Value = timing. Step (value );
}
Return value;
}

Public int callreflectargs (INT loops) throws exception {
Timingclass timing = new timingclass ();
Try {
Method method = timingclass. Class. getmethod
("Step", new class [] {Int. Class });
Object [] ARGs = new object [1];
Object value = new INTEGER (0 );
For (INT Index = 0; index <loops; index ++ ){
ARGs [0] = value;
Value = method. Invoke (timing, argS );
}
Return (integer) value). intvalue ();
} Catch (exception ex ){
System. Out. println ("Error Using Reflection ");
Throw ex;
}
}


Reflection performance is an important aspect of Sun's 1.4 JVM development. It is displayed in the reflection method call results. In terms of the performance of such operations, Sun 1.4.1 JVM shows great improvements over version 1.3.1. In my tests, the running speed is about the start of Version 1.3.1. In such a simple test, the IBM 1.4.0 JVM again achieved better results, but only two to three times faster than sun 1.4.1 JVM.

I also wrote a similar timing test program for the creation of objects using reflection, but the difference in this case is not as significant as in the case of field and method calls. Use newinstance () to create a simple Java. lang. the time consumed by the object instance is about 12 times that of using new object () on Sun 1.3.1 JVM, four times that of IBM 1.4.0 JVM, but two times that of Sun 1.4.1 JVM. Use array. newinstance (type, size) consumes twice the time to create an Array Using New Type [size] on any tested JVM. As the array size increases, the difference gradually decreases.

Conclusion
Java reflection provides a multi-functional method for dynamically linking program components. It allows programs to create and control objects of any class (according to security restrictions), without the need to hard-code the target class in advance. These features make reflection especially suitable for creating libraries that work with objects in very common ways. For example, reflection is often used in frameworks where the continuously stored object is in a database, XML, or other external format.

Reflection has two disadvantages. The first is performance issues. When used for field and method access, reflection is much slower than direct code. The degree of performance problems depends on how reflection is used in the program. If it is a relatively small part of the program running, slow performance will not be a problem. The reflection operation shown in the timing chart in the worst case of the test takes only a few microseconds. Performance issues are crucial only when reflection is used in the core logic of performance-critical applications.

One of the more serious disadvantages of many applications is that reflection will blur what actually happens inside the program. Programmers want to see the program logic in the source code, reflection and other technologies that bypass the source code will cause maintenance problems. Reflection code is more complex than the corresponding direct code, as seen in code instances with better performance. The best solution to these problems is to use reflection conservatively-only where it can actually increase flexibility-record its use in the target class.

In the next section, I will provide more detailed examples of how to use reflection. This type of instance provides an API for processing Java application command line parameters, a tool that you may find suitable for your own applications. It is also created based on the advantages of reflection, while avoiding its weaknesses. Does reflection simplify your command line processing? You can find the answer in Java programming Dynamics Section 3rd.

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.