This discussion is archived
12 Replies Latest reply: May 18, 2013 11:57 AM by baftos RSS

Behavior of Private & Final instance variable while working with Reflection

user11436730 Newbie
Currently Being Moderated
Using reflection , I am able to successfully access the private members of the Class A using following snippet :
package com.test;

public class A {

     
     private int _count = 0;
     public A() {
          
     }
     
     public void setCount(int count) {
          if ( count < 0){
               System.err.println("Value must be positive.");
               return;
          }
          _count = count;
     }
     
     public int getCount() {
          return _count;
     }
     
}
package com.test;

import java.lang.reflect.Field;

public class MainClass {

     private static Field f = null;
     A a  = null;
     static {
          try {
               
               f = A.class.getDeclaredField("_count");
               if ( f != null)
                    f.setAccessible(true);
               
          } catch (NoSuchFieldException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (SecurityException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
          
     }
     
     
     public MainClass() {
          
          a = new A();
          
          if ( f != null ) {
               try {
                    f.set(a, -99);
               } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
          }
          
     }
     
     public void printCount() {
          
          System.out.println("Total Count : " + a.getCount());
          
     }
     
     public static void main(String[] args) {
          
     
          MainClass cls = new MainClass();
          cls.printCount();
          
          
     }
     
}
The above code is working fine, but when I tried the same thing with provided class like java.lang.String and tried access the private member of it, it threw an exception for access. Though the access can be restricted by setting SecurityManager which I tried in my case also and worked , but in java.lang.String I was unable to find any implementation for the SecurityManager which disallowed the access to private members, then how is it that I am not able to access it using reflection?

Also in the same above example,when I made by _count variable as final, and tried changing the value using reflection it did not threw any exception at runtime but did not change value either.

Appreciate any help on enhancing the understanding on this.

Thanks in advance.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points