Java-reflection depth profiling

Source: Internet
Author: User

Java reflection is an important feature of the Java language. It briefly analyzes the definition, principles, usage, performance, and application scenarios of reflection.

(1) Definition

When a program is running, the program structure or variable type can be modified. This language is called Dynamic Language. Java is not a dynamic language, but provides RTTI (Run-time Type Identification) runtime class recognition. RTTI can be divided into two methods: known during compilation and running, and reflection.


(Ii) Principle

As mentioned in "deep into java Virtual Machine", java files are compiled into class files, added to the JVM class loader, and the Class bytecode is loaded to the method area, and class classes are generated in the heap, the Class can access the basic information of the Class, such as the simple name of the Class, the Class containing the full name of the path, the access modifier, field, method, and other information.

Classes to be used in reflection:

Field Class: provides information about the attributes of a class or interface and its dynamic access permissions. The reflected field may be a class (static) attribute or instance attribute. A simple understanding of it can regard it as a class that encapsulates the attributes of the reflection class.
Constructor class: Provides information about a single Constructor of the class and its access permissions. This class is different from the Field class. The Field class encapsulates the attributes of the reflection class, while the Constructor class encapsulates the Constructor method of the reflection class.
Method class: Provides information about a separate Method on a class or interface. The reflected methods may be class methods or instance methods (including abstract methods ).
Class: an instance of a Class indicates the classes and interfaces in a running Java application. Enumeration is a type, and annotation is an interface. Each array is a Class mapped to a Class Object. All arrays with the same element type and dimension share the Class object.


(3) Use

(1) obtain the Class

Method 1: Class c = Class. forName ("java. lang. String ")
Method 2: for basic data types, statements such as Class c = int. class or Class c = Integer. TYPE can be used.

(Tips: int. class = Integer. TYPE! = Integer. class)

Method 3: Class c = MyClass. class

(2) Call the methods in the Class to get the information set you want. For example, call the getDeclaredFields () method to get all the attributes of the Class.

Field field = classInstance.getDeclaredField("TEST_TIMES");            int times = (Integer) field.get(classInstance);            System.out.println(times);


(4) Performance

The performance of reflection is lower than that of direct calls. This result will be verified by the next test. Try to avoid interference factors such as object creation during the test.

We will test the time consumed for direct access, the time consumed for direct reflection, the time consumed for caching the function reflection to be searched, and the time consumed for reflection using ReflectAsm.

/*** Test the reflection performance ** @ author peter_wang * @ create-time 12:54:52 */public class ReflectPerformanceDemo {private static final int TEST_TIMES = 1000000; private long mNum; private long mSum;/*** @ param args */public static void main (String [] args) {normalInvoke (); normalReflectInvoke (); cacheReflectInvoke (); asmReflectInvoke ();}/*** normal call Method */private static void normalInvoke () {ReflectPerformanceDemo demo = new ReflectPerformanceDemo (); long time1 = System. currentTimeMillis (); for (long I = 0; I <TEST_TIMES; I ++) {demo. setmNum (I); demo. mSum + = demo. getmNum ();} long time2 = System. currentTimeMillis (); System. out. println ("normal invoke time:" + (time2-time1);}/*** common reflection call Method */private static void normalReflectInvoke () {ReflectPerformanceDemo demo = new ReflectPerformanceDemo (); long time1 = System. currentTimeMillis (); try {for (long I = 0; I <TEST_TIMES; I ++) {Class
 C = Class. forName ("com. peter. demo. process. reflect. reflectPerformanceDemo "); Method method = c. getMethod ("setmNum", Long. TYPE); method. invoke (demo, I); demo. mSum + = demo. getmNum () ;}} catch (Exception e) {e. printStackTrace ();} long time2 = System. currentTimeMillis (); System. out. println ("normal reflect invoke time:" + (time2-time1);}/*** cache reflection call Method */private static void cacheReflectInvoke () {ReflectPerformanceDemo demo = new ReflectPerformanceDemo (); try {Class
 C = Class. forName ("com. peter. demo. process. reflect. reflectPerformanceDemo "); Method method = c. getMethod ("setmNum", Long. TYPE); long time1 = System. currentTimeMillis (); for (long I = 0; I <TEST_TIMES; I ++) {method. invoke (demo, I); demo. mSum + = demo. getmNum ();} long time2 = System. currentTimeMillis (); System. out. println ("cache invoke time:" + (time2-time1);} catch (Exception e) {e. printStackTrace () ;}}/*** asm reflection call Method */private static void asmReflectInvoke () {ReflectPerformanceDemo demo = new ReflectPerformanceDemo (); try {MethodAccess ma = MethodAccess. get (ReflectPerformanceDemo. class); int index = ma. getIndex ("setmNum"); long time1 = System. currentTimeMillis (); for (long I = 0; I <TEST_TIMES; I ++) {ma. invoke (demo, index, I); demo. mSum + = demo. getmNum ();} long time2 = System. currentTimeMillis (); System. out. println ("asm invoke time:" + (time2-time1);} catch (Exception e) {e. printStackTrace () ;}} public long getmNum () {return mNum;} public void setmNum (long mNum) {this. mNum = mNum ;}}

Test results:

normal invoke time:7normal reflect invoke time:1499cache invoke time:32asm invoke time:20

The cache-based reflection calling method is much slower than direct calling. Using the asm third-party reflection library, the speed has been slightly improved.

Cause of slow reflection: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be written med. consequently, reflective operations have slower performance than their non-reflective counterparts, and shocould be avoided in sections of code which are called frequently in performance-sensitive applications.


(5) application scenarios

(1) Component-based programming: in this way, a Rapid Application Development (RAD)-based application building tool will be used to build a project. This is now the most common visual programming method. You can drag the icons representing different components to the graph board to create programs, and then set the attribute values of the components to configure them. This configuration requires that all components are instantiated and some of their information should be exposed so that programmers can read and set the values of the components.

(2) provides the ability to create and run objects on a remote platform across networks to achieve Network Mobility in java. This is called Remote Call (RMI), which allows a Java program to put objects on multiple machines step by step. This step-by-step capability will help developers execute tasks that require a large amount of computing, make full use of computer resources to increase the running speed.


(6) Example

The most reliable Singleton mode is cracked. In this example, lazy loading is the fifth Singleton mode, but the reflection mechanism can be used to break the security.

/*** Safe Singleton mode ** @ author peter_wang * @ create-time 4:45:20 */public class SingletonSafe {private SingletonSafe () {System. out. println ("create singleton");} private static class StaticSingleton {private static SingletonSafe instance = new SingletonSafe ();} public static SingletonSafe getInstance () {return StaticSingleton. instance ;}}
/*** Test reflection *** @ author peter_wang * @ create-time 5:08:58 */public class ReflectDemo {/*** @ param args */public static void main (String [] args) {try {Class classInstance = Class. forName ("com. peter. demo. process. reflect. singletonSafe "); System. out. println (classInstance. getName (); Constructor cons = classInstance. getDeclaredConstructor (null); cons. setAccessible (true); SingletonSafe singletonSafe1 = (SingletonSafe) cons. newInstance (null); System. out. println ("singleton1:" + singletonSafe1.toString (); SingletonSafe singletonSafe2 = (SingletonSafe) cons. newInstance (null); System. out. println ("singleton2:" + singletonSafe2.toString (); Method method1 = classInstance. getDeclaredMethod ("getInstance", null); SingletonSafe singletonSafe3 = (SingletonSafe) method1.invoke (classInstance, null); System. out. println ("singleton3:" + singletonSafe3.toString (); Method method2 = classInstance. getDeclaredMethod ("getInstance", null); SingletonSafe singletonSafe4 = (SingletonSafe) method2.invoke (classInstance, null); System. out. println ("singleton4:" + singletonSafe4.toString ();} catch (Exception e) {e. printStackTrace ();}}}

Test results:

com.peter.demo.process.reflect.SingletonSafecreate singletonsingleton1:com.peter.demo.process.reflect.SingletonSafe@2a9931f5create singletonsingleton2:com.peter.demo.process.reflect.SingletonSafe@2f9ee1accreate singletonsingleton3:com.peter.demo.process.reflect.SingletonSafe@5f186fabsingleton4:com.peter.demo.process.reflect.SingletonSafe@5f186fab

According to the test results,
In Singleton mode, you can use reflection to create multiple objects.


(7) Summary

At present, the speed of computer systems, application development is no longer too concerned about performance, but more focused on system maintainability and scalability, and rapid development efficiency. The above test results are generated based on a large number of operations. In a common business request, reflection is usually used for a very small number of times and is only used at the framework level. In a high-load system, the performance of business processing will be the key point, not the performance impact caused by these reflection. The value of the Development convenience and maintainability extensibility brought by reflection is much higher than the loss of performance.



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.