Where do I put javaassist code?

Posted by DutrowLLC on Stack Overflow See other posts from Stack Overflow or by DutrowLLC
Published on 2010-06-13T22:35:56Z Indexed on 2010/06/13 22:42 UTC
Read the original article Hit count: 266

Filed under:
|
|

I have an application running on google app engine. I'm using restlets and I have a couple of layers set up including the restlet layer, the model layer, the business layer, and the data layer.

I'm attempting to use javaassist to modify some classes, but I'm unsure where to actually put the code. I tried to put the code in the static initialization block:

public class Person {

     String firstName;
     String getFirstName(){return null;}

     static{
          ClassPool pool = ClassPool.getDefault();
          try {
               CtClass CtPerson = pool.get("Person");
               CtMethod CtGetFirstName = CtPerson.getDeclaredMethod("GetFirstName");
               CtGetFirstName.setBody("return firstName;");
               CtPerson.toClass();
          } catch (Exception e) {
               e.printStackTrace();
          }
     }
}

...but that resulted in this error: javassist.CannotCompileException:.....attempted duplicate class definition...". I guess it makes sense that I can't edit the class file in the middle of its generation.

I know the code works because I was able to run it correctly by simply putting it in a location that would run when I sent the program a command. (accessed a Restlet resource). The code ran fine if an instance of the class had not already been instantiated, however once I instantiated an instance of the affected class, the javaassist code failed.

I assume I need to put this code somewhere that it will only run either: once after the program starts, directly before a class is instantiated for the first time, or even better, during compile time.

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection