Archive for July, 2009

How to access a private field in java

This was a question posted in StackOverflow.
I didn’t know this was possible, so i am posting the answer provided by oxbow_lakes as is:

In order to access private fields, you need to get them from the class’s declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField(“stuffIWant”); //NoSuchFieldException
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value will all throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField(“misspelled”); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM’s SecurityManager will not allow you to change a field’s accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field’s class’s type:

f.get(“BOB”); //will throw IllegalArgumentException, as String is of the wrong type

I advise you to go read the question and the answers at SO :

Categories: java Tags: ,

Compile Code in a different encoding with wlcompile

If you wish to compile code encoded differently you can just add the following javac option to your wlcompile call:

<javac encoding=”UTF-8″ />

just replace UTF-8 with whatever encoding you want to treat your code has.

you can add this option like you add any other javac option, example taken from here :

<wlcompile srcdir=”${mysrcdir}” destdir=”${mybuilddir}”>

<javac deprecation=”false” debug=”true”¬†¬†¬†debuglevel=”lines,vars,source”/>


Some info here and here

this answer in StackOverflow may also interest you.

Categories: java, weblogic