1 Reply Latest reply on Jul 9, 2008 4:44 AM by Ruth Alkema

    Problem Instrumenting System classes

    Suman K Newbie

      Hi all,

      I am trying to instrument java.lang.String class. For starters, I tried using the example code in the javassist manual, but it doesn't seem to work.

      The class that adds a new field to the java.lang.String is as follows:

      package sample;
      import javassist.*;
      public class AddFieldToString {
       public int f(int i) {
       return i + 1;
       public static void main(String[] args) throws Exception {
       ClassPool pool = ClassPool.getDefault();
       CtClass cc = pool.get("java.lang.String");
       cc.addField(new CtField(CtClass.intType, "hiddenValue", cc));

      A sample application is as follows:

      package sample;
      public class MyApp {
       public static void main(String[] args) throws Exception {

      After compiling and running the above program as shown below, I get a FieldNotFound exception.

      ./installs/javassist-3.8.0 % rm -rf ./java ;
      j javac -cp javassist.jar sample/AddFieldToString.java ;
       java -cp .:javassist.jar sample/AddFieldToString ;
       javac sample/MyApp.java ;
       java -Xbootclasspath/p:. sample/MyApp
      Exception in thread "main" java.lang.NoSuchFieldException: hiddenValue
       at java.lang.Class.getField(Class.java:1507)
       at sample.MyApp.main(MyApp.java:5)

      I am sure that the generated code has a something about hidden field, but the decompiler is unable to find it too:

      ./installs/javassist-3.8.0 % cat java/lang/String.class | grep hiddenValue
      Binary file (standard input) matches
      /installs/javassist-3.8.0 % javap java/lang/String | grep hiddenValue

      Am I missing something obvious? Any pointers would be helpful. Thanks for your time.

        • 1. Re: Problem Instrumenting System classes
          Ruth Alkema Newbie

          hi, I just ran into the same thing. But I have managed to solve it eventually..

          The problem is, that hiddenValue is not a public field, so the MyApp.java should call getDeclaredField instead of getField.

          And the fact that javap doesn't see it, is because it reads the String.class from the rt.jar.
          If you call

          javap -bootclasspath <path.to.new.string> java.lang.String
          then you will see the 'hiddenValue' field