Java reflection change constants, and their limitations

Source: Internet
Author: User

Problem. And a way to solve

Today, the company's Java project encountered a problem: when generating the XLS file, assume that the data is more. There will be arrayindexoutofboundsexception.


Google Discovery is the JXL package used in the item (open Source Library. A bug that is used to process the XLS file).


Also found a solution to the method: http://www.blogjava.net/reeve/archive/2013/01/11/114564.html--that is to find its source. A static constant in the change. And then you can pack it into a jar again. Try it, this method is really feasible.

There is also a solution-reflection

But later in the company's predecessors remind, can try--

Take advantage of Java's reflection. Force changes to the values we need when we execute the constants that need to be changed

-so you don't have to change the JXL library. Just add a few sentences to our project and the probability of the problem will be very small.
So I studied it, even though it was the end of the day. This method is not feasible in our project. It's just a very rewarding one.

First, the method of changing private static constants using reflection is for example the following Bean class. The Int_value is a private static constant
Class bean{    private static final Integer int_value = 100;}
Change the core code of the constant:
    System.out.println (bean.int_value);    Gets the Int_value field of the Bean class fields field    = Bean.class.getField ("Int_value");    Set the access permission for a field to true: the effect of removing the private modifier    field.setaccessible (true);    /* Removes the effect of the final modifier. Set the field to a modified *    /Field Modifiersfield = Field.class.getDeclaredField ("modifiers");    Modifiersfield.setaccessible (true);    Modifiersfield.setint (field, Field.getmodifiers () & ~modifier.final);    Set the field value to    field.set (null, max);    System.out.println (Bean.int_value);

The result of the above code output is:

100
200

The description was successful with the reflection private static constant.

Limitations of the programme

Note that the static constant type in the above code is integer--but the field type that we actually need to change in our project is not the wrapper type integer, but the basic type int of java.
After you change the type of the constant to int,

Class bean{    private static final int int_value = 100;//changed the type from integer to int}

In the case where no other code is changed. The results of the code output turned out to be bizarre:

100
100

and found in the process of debugging. At the time of the second output. The Bean.int_value in memory has become 200, but the result of System.out.println (Bean.int_value) output is still weird 100?!

-Does the reflection fail?

Again, several other types have been tried, and it is found that such seemingly defunct situations occur on the basic types of int, long, Boolean, and string. It is assumed that the type is changed to a wrapper type such as an integer, Long, Boolean, or otherwise, such as date and object, will not fail.

Reason

Through a series of research, guessing, search and other processes. Finally found the reason:

For static constants of the basic type, Java is compiled to replace the reference in this constant with the corresponding constant value in the code.

References: Modifying final fields in Java
That is, for constant public static final int maxformatrecordsindex = 100, the code

if (Index > Maxformatrecordsindex   ) {    index  =  maxformatrecordsindex;}     

This code has been actively optimized by Java itself when compiling it:

if (Index >) {    index = 100;}

So when Int_value is the int type,

System.out.println (Bean.int_value);//compile will be optimized to the following: System.out.println (100);

So, naturally. No matter how the change boolean.int_value,system.out.println (Bean.int_value) will still be stubbornly output 100.

-This itself is a behavior of the JVM's optimized code to improve execution efficiency. But it will cause us to use reflection to change this constant value when there is a similar illusion that does not take effect.

This is probably a limitation of Java reflection-it's not too reliable to change the constants of basic types. Just attach the demo code I tested.

Import Java.lang.reflect.field;import Java.lang.reflect.modifier;import Java.util.date;public class ForClass {static        void setfinalstatic (Field field, Object newvalue) throws Exception {field.setaccessible (true);        Field Modifiersfield = Field.class.getDeclaredField ("modifiers");        Modifiersfield.setaccessible (TRUE);        Modifiersfield.setint (field, Field.getmodifiers () & ~modifier.final);    Field.set (null, newvalue);        } public static void Main (String args[]) throws Exception {System.out.println (bean.int_value);        Setfinalstatic (Bean.class.getField ("Int_value"), 200);        System.out.println (Bean.int_value);        System.out.println ("------------------");        System.out.println (Bean.string_value);        Setfinalstatic (Bean.class.getField ("String_value"), "string_2");                System.out.println (Bean.string_value);        System.out.println ("------------------");        System.out.println (Bean.boolean_value); SetfinaLstatic (Bean.class.getField ("Boolean_value"), true);        System.out.println (Bean.boolean_value);        System.out.println ("------------------");        System.out.println (Bean.object_value);        Setfinalstatic (Bean.class.getField ("Object_value"), New Date ());    System.out.println (Bean.object_value);    }}class Bean {public static final int int_value = 100;    public static final Boolean Boolean_value = false;    public static final String string_value = "string_1"; public static final Object Object_value = "234";}
Code output
100100------------------string_1string_1------------------falsetrue------------------234Fri Apr 00:55:05 CST 2014

Description

--The Boolean and object type constants are correctly modified, and the changes to the primitive type int and string "are not in effect."

Sync Posted in http://www.barryzhang.com/archives/188

Advertise my new blog. Welcome to the Interview ha ~:barryzhang.com

Java reflection change constants, and their limitations

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.