Home > Java > Adding awesomeness on the run with javassist

Adding awesomeness on the run with javassist

January 17th, 2012 Leave a comment Go to comments

Creating new classes during runtime can be nice when you need it. Below is a small example of what is possible. (No interface or existing base class is used in this example so reflection is required to invoke a method)

ClassPool classPool = ClassPool.getDefault();
CtClass cc = classPool.makeClass("AwesomeNewClass");
cc.addMethod(CtMethod.make("public String getValue() { return \"Hello World!\"; }", cc));
Class awesome = cc.toClass();
Object o = awesome.newInstance();
 
Method method = awesome.getMethod("getValue");
String returnValue = (String) method.invoke(o);
Categories: Java Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.