[Spoon-discuss] Exception inserting code when if-statement body has no curly braces

Alex Epshteyn alexander.epshteyn at gmail.com
Sun Jan 4 00:28:03 CET 2009


I'm trying to insert some code before every return statement in each
method.  There is a problem when a return statement occurs inside a
block with no curly braces like this:


  /** Spoon throws an exception when trying to instrument a block with
no curlies around it */
  public void foo(int x) {
    if (x < 0)
      return;  // will fail here
    if (x == 0)  {
      return;  // this is OK because curly braces present
    }
    else
      positive(xStr);
  }

Spoon throws:

java.lang.ClassCastException: spoon.support.reflect.code.CtIfImpl
cannot be cast to spoon.reflect.code.CtBlock
	at spoon.support.reflect.code.CtStatementImpl.insertBefore(CtStatementImpl.java:78)


Here is my Processor code:

public void process(CtMethod method) {
    ...
    // instrument all return statements
    // TODO: if statements without curly braces will throw an
exception: java.lang.ClassCastException:
spoon.support.reflect.code.CtIfImpl cannot be cast to
spoon.reflect.code.CtBlock

    method.getBody().insertBefore(
        new TypeFilter<CtReturn>(CtReturn.class),
        Substitution.substituteMethodBody(
            (CtClass) method.getDeclaringType(),
            createTemplate(methodId, paramNames), "endMethod"));
   }


I'm using Spoon 1.4.  Would appreciate your assistance in finding a
workaround to this problem.

Thanks,
Alex




More information about the Spoon-discuss mailing list