0

I try to add an "assert" statement to a method.

But I get this exception:

Caused by: compile error: assert(boolean) not found in mypackage.MyClassThatIsInstrumented at javassist.compiler.TypeChecker.atMethodCallCore(TypeChecker.java:716) at javassist.compiler.TypeChecker.atCallExpr(TypeChecker.java:681) at javassist.compiler.JvstTypeChecker.atCallExpr(JvstTypeChecker.java:156) at javassist.compiler.ast.CallExpr.accept(CallExpr.java:45) at javassist.compiler.CodeGen.doTypeCheck(CodeGen.java:241) at javassist.compiler.CodeGen.atStmnt(CodeGen.java:329) at javassist.compiler.ast.Stmnt.accept(Stmnt.java:49) at javassist.compiler.CodeGen.atStmnt(CodeGen.java:350) at javassist.compiler.ast.Stmnt.accept(Stmnt.java:49) at javassist.compiler.CodeGen.atMethodBody(CodeGen.java:291) at javassist.compiler.Javac.compileBody(Javac.java:222) at javassist.CtBehavior.setBody(CtBehavior.java:360) ... 30 more

Any ideas how to solve that?

cedarsoft
  • 11
  • 3

1 Answers1

0

A workaround is to implement the assertion as a conditional:

 if(Foo.class.desiredAssertionStatus() && expr) {
   throw new AssertionError();
 }

This is basically equivalent to

 assert expr;

Now it is a matter of how you would like to inject it. If you need to assert against the method parameters, you can use method.insertBefore(); if you're asserting the result, you can use method.insertAfter().

If the statement needs to be inserted into the method's body, somewhere in between the statements, then you can use ExprEditor to match the required statement where you want this new statement to be injected

Anton Arhipov
  • 6,479
  • 1
  • 35
  • 43