java - Update private static final int in base class for unittest -


i try change int value of private static final int unittesting. looked @ http://zarnekow.blogspot.de/2013/01/java-hacks-changing-final-fields.html , http://java-performance.info/updating-final-and-static-final-fields/ , other stackoverflow examples like: changing final variables through reflection, why difference between static , non-static final variable

30 seconds default timer. want set setoverreflectionmax_seconds(3); 3 seconds. but not work, hints ?

my baseclass

public class baseclass {      private static final int max_seconds = 30;  } 

and other class

public final class myclass extends baseclass {      public static list<field> getfields(final class<?> clazz){         final list<field> list = new arraylist<>();         list.addall(arrays.aslist(clazz.getdeclaredfields()));          if(clazz.getsuperclass() != null){             list.addall(getfields(clazz.getsuperclass()));         }         return list;     }      public static void setoverreflectionmax_seconds(final int newvalue) {          final list<field> fields = getfields(myclass.class);         (final field field : fields) {             if (field.getname().equals("max_seconds")) {                  field.setaccessible(true);   //edit 4                   field modifiersfield;                 try {                     modifiersfield = field.class.getdeclaredfield("modifiers");                     modifiersfield.setaccessible(true);                     modifiersfield.setint(field, field.getmodifiers() & ~modifier.final);                     field.set(null, newvalue);                 } catch (final exception e2) {                     e2.printstacktrace();                 }              }         }     }  } 

edit1: wrong classname

edit2: cant change baseclass (got .class file)

edit3: new exception

class myclass can not access member of class baseclass modifiers "private static" 

edit4 : see code , fixes exception, not change int

this may not possible using reflection, because value of field may inlined compiler (i believe compiler free choose whether or not). in case, copy of value hardcoded used, , can changed manipulating byte code.

this explained in more detail in question: change private static final field using java reflection.

tl,dr: there no way reliably change static final field using reflection. options are:

  • manipulate byte code (a rather desperate option)
  • find solution (subclass, wrapper, proxy...)
  • (bug author to) change source code, make value settable/configurable

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -