Reputation: 49
I am using Javassist to write a HelloWorld class with main method. When I compile , I get an error as below. I am not sure what's wrong with String[] args in the main method ?
javassist.CannotCompileException: [source error] syntax error near "ng[] args)"
at javassist.CtNewMethod.make(CtNewMethod.java:78)
at javassist.CtNewMethod.make(CtNewMethod.java:44)
This is my code
public void createClass() {
ClassPool cp = ClassPool.getDefault();
CtClass ct = cp.makeClass("HelloClass");
try {
CtMethod m = CtNewMethod.make("public void sayHello() { System.out.println(\"Hello World\");}",ct);
ct.addMethod(m);
String str="public static void main(String[] args)";
CtMethod n = CtNewMethod.make(str,ct);
n.setBody("HelloClass a = new HelloClass();a.sayHello();");
ct.addMethod(n);
ct.writeFile();
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void main(String[] args) {
JavaAssistExample inject = new JavaAssistExample();
inject.createClass();
}
Upvotes: 1
Views: 1263
Reputation: 280138
As the javadoc for CtNewMethod
states
The source code must include not only the method body but the whole declaration
It must therefore contain the {}
, like
String str = "public static void main(String[] args){}";
However, two more things will give you problems.
First, you don't have a default (or a no arg) constructor. Add one
ct.addConstructor(CtNewConstructor.defaultConstructor(ct));
Second, the CtMethod#setBody(..)
method completely replaces the method body. So you can't do what you are doing. If you want all of those calls, you'll need to put them together
n.setBody("{HelloClass a = new HelloClass();a.sayHello();}");
Upvotes: 2