access private fields

May 16, 2007 13:20


two classes Constant and MainClass

public class Constant {
 public static int number = 10;
}

import java.lang.reflect.*;

public class MainClass {
 public static void main(String[] args) {
  try {
   System.out.println(Modifier.toString(Constant.class.getDeclaredField("number").getModifiers()));
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println("Constant.number:" + Constant.number);
 }
}

compile: javac Constant.java MainClass.java

run MainClass::
 >java MainClass 
 public static
 Constant.number:10

change Constant.number to private and recompile it
public class Constant {
 prvate static int number = 10;
}

compile: javac Constant.java

and run:
 >java MainClass
 private static
Constant.number:10

Previous post Next post
Up