问题
I'm trying to write some Bytecode manipulation in my web application now when I try to inject my code into my methods it always throws me the error
javassist.CannotCompileException: [source error] ) is missing
I don't know why and what this is ... I've googled a bit and some people say It's a bug from version 1.0 javassist but I thinks that's really unrealistic.
private void changeMethod(CtMethod method) throws NotFoundException,
CannotCompileException {
if (method.hasAnnotation(Loggable.class)) {
method.getName();
method.insertBefore("long startTime = 0;" +
"long startTime = System.currentTimeMillis();" +
" Thread thread1 = new Thread(new Runnable(){\n" +
" @Override\n" +
" public void run() {\n" +
" threadLogger.info(\"Testlog\");\n" +
"\n" +
" try {\n" +
" threadLogger.logCall(Webservice.this.getClass().getMethod(startThread0), \"Thread\");\n" +
" \n" +
" } catch (Exception e) {\n" +
" e.printStackTrace();\n" +
" }\n" +
"\n" +
" }\n" +
" });\n" +
" thread1.start();");
}
}
enter code here
回答1:
As you can read in the Javassist documentation, section 4.7 Limitations (bold is mine):
Inner classes or anonymous classes are not supported. Note that this is a limitation of the compiler only. It cannot compile source code including an anonymous-class declaration. Javassist can read and modify a class file of inner/anonymous class.
You are attempting to inject an anonymous Runnable class, so it won't work. Your best way around this issue is to extract the Runnable class code to a new class that is available in the classpath at injection and runtime and use that class in the injection code.
回答2:
Refers to compilation errors in the source code inside the string. The first problem I can spot is that you have
long startTime = 0;
long startTime = System.currentTimeMillis();
You are defining the variable twice and this won't compile.
Overall the easiest way I have found to write Javassist code is to copy this from your IDE class. This will help you spot most of the problems and can save you some time debugging code in Strings. Of course it is not perfect because most of the time the code won't compile in the IDE because it is referencing something that will work only in code insertion point but it will find problems like double variable etc.
回答3:
I wrote a Method now and just injectet the method with bytecode manipulation ... was the simplest resolution.
来源:https://stackoverflow.com/questions/31649970/javassist-cannotcompileexception-source-error-is-missing-what-is-this