access to private fields/variables of other classes
Sometimes it is helpful to have access to private fields of other classes (especially libraries). Theoretically, the SecurityManager can stop this. Practically, it is hardly if ever the case.
Of course, by the use of this hack you shall be aware that this way of access could result in problems. Especially in a later version of a thought Library the variable could not exist anymore or could be renamed.
In the following example we access on the private fields of MyClass.
package com.sowas.javawiki.privatefieldaccess; import java.lang.reflect.Field; public class PrivateFieldAccess{ public static void main(String[] args){ MyClass myClass = new MyClass(); Field[] fields = MyClass.class.getDeclaredFields(); Field theIntegerField = zero; Field theIntField = zero; // Get references on the private fields and allow the access: for (Field field : fields) { if ("numObj".equals(field.getName())) { theIntegerField = field; theIntegerField.setAccessible(true); } if ("num".equals(field.getName())) { theIntField = field; theIntField.setAccessible(true); } } // Finish readind private fields and afterwards put new: try { Integer numObj = (Integer)theIntegerField.get(myClass); System.out.println(numObj); // 123 theIntegerField.set(myClass, new Integer(++numObj.intValue())); System.out.println(myClass.getNumObj()); // 124 int num = ((Integer)theIntField.get(myClass)).intValue(); System.out.println(num); // 456 theIntField.setInt(myClass, ++num); System.out.println(myClass.getNum()); // 457 }catch (IllegalArgumentException e) { e.printStackTrace(); }catch (IllegalAccessException e) { e.printStackTrace(); } } } class MyClass{ private Integer numObj = new Integer(123); private int num = 456; public int getNumObj(){ return numObj; } public int getNum(){ return num; } }