Adding awesomeness on the run with javassist
January 17th, 2012
No 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); |