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));
cc.writeFile(".");
}
}
A sample application is as follows:
package sample;
public class MyApp {
public static void main(String[] args) throws Exception {
System.out.println(String.class.getField("hiddenValue").getName());
}
}
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.