Java reflection call Optimization

Source: Internet
Author: User

When writing some Java frameworks, you often need to get or set the field of a bean through reflection. A common practice is to obtain the field and call Java. lang. reflect. field. get (object), but does it have room for optimization every time it is called like this?

 

The answer is yes.

First:

Because every call is repeated, I think of caching the field of each bean, but this is not enough, so I thought of writing a code generator. By generating code, the getter or setter of the bean can be directly called during get or set every bean. This implementation sounds awesome, in fact, it is enough to use ASM to generate a class and load it with a classloader to directly invoke each call.

It is possible to do so much for a reflection call, and the general feeling is that the cannon is hitting a mosquito.

 

Second:

Thanks to @ redna xelafx, we have found a simpler method: Sun. Misc. unsafe.

It is also very easy to use: first, use sun. misc. unsafe. objectfieldoffset (field) to get the field offset, and then use sun. misc. unsafe. getObject (object, long) obtains the field value of an instance.

Hessian uses this method for Java object serialization and deserialization! For details, see COM. Caucho. Hessian. Io. hessianinput, Com. Caucho. Hessian. Io. hessianoutput. What is the difference in efficiency between these methods? Try again later!

The simple test code for sun. misc. Unsafe is as follows:

import java.io.Serializable;import java.lang.reflect.Field;import sun.misc.Unsafe;/** * @author haitao.yao Dec 14, 2010 */public class ReflectionCompare {private static final int count = 10000000;/** * @param args */public static void main(String[] args) {long duration = testIntCommon();System.out.println("int common test for  " + count+ " times, duration: " + duration);duration = testUnsafe();System.out.println("int unsafe test for  " + count+ " times, duration: " + duration);}private static long testUnsafe() {long start = System.currentTimeMillis();sun.misc.Unsafe unsafe = getUnsafe();int temp = count;Field field = getIntField();long offset = unsafe.objectFieldOffset(field);while (temp-- > 0) {unsafe.getInt(new TestBean(), offset);}return System.currentTimeMillis() - start;}private static long testIntCommon() {long start = System.currentTimeMillis();int temp = count;getIntField().setAccessible(true);while (temp-- > 0) {TestBean bean = new TestBean();try {getIntField().get(bean);} catch (Exception e) {e.printStackTrace();}}return System.currentTimeMillis() - start;}private static final sun.misc.Unsafe unsafe;static {sun.misc.Unsafe value = null;try {Class<?> clazz = Class.forName("sun.misc.Unsafe");Field field = clazz.getDeclaredField("theUnsafe");field.setAccessible(true);value = (Unsafe) field.get(null);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("error to get theUnsafe", e);}unsafe = value;}public static final sun.misc.Unsafe getUnsafe() {return unsafe;}private static final Field intField;private static final Field stringField;static {try {intField = TestBean.class.getDeclaredField("age");stringField = TestBean.class.getDeclaredField("name");} catch (Exception e) {e.printStackTrace();throw new IllegalStateException("failed to init testbean field", e);}}public static final Field getIntField() {return intField;}public static final Field getStringField() {return stringField;}/** * @author haitao.yao Dec 14, 2010 */static class TestBean implements Serializable {/*** */private static final long serialVersionUID = -5994966479456252766L;private String name;private int age;/** * @return the name */public String getName() {return name;}/** * @param name *            the name to set */public void setName(String name) {this.name = name;}/** * @return the age */public int getAge() {return age;}/** * @param age *            the age to set */public void setAge(int age) {this.age = age;}}}

Http://hi.baidu.com/hellolq/item/26493d1efe2b066a71d5e89d.

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.