4 Replies Latest reply on Aug 17, 2005 12:33 PM by chiba

    Error Compiling a switch

    jammerie

      Hi All,

      I was trying to compile a new Method using the CtNewMethod class and hit a problem, compiling the following switch statement:

      public static final int TWO = 2;
      ...
      ...
      switch (mode) {
      case 1: System.out.println ("1");
      case TWO: System.out.println ("2");
      }

      when it tried to compile case TWO: it always throws an compile exception with "Bad case Label". I traced the source down to CodeGen.java and it only compile for IntConst and not Member. So I have the following code now:

      private int computeLabel(ASTree expr) throws CompileError {
      doTypeCheck(expr);
      expr = TypeChecker.stripPlusExpr(expr);
      if (expr instanceof IntConst)
      return (int)((IntConst)expr).get();
      else if (expr instanceof Member) {
      Object returnValue = (Integer) ((Member) expr).getField().getConstantValue();
      if (returnValue != null) {
      if (returnValue instanceof Integer)
      return ((Integer) returnValue).intValue();
      }
      }
      throw new CompileError("bad case label");
      }


      Now I detected anoher problem which I cannot solve. If I add in CtField public static final int TWO = 2; during runtime, the method call getConstantValue () will return a null. I tried using javaassist to modify the class and then load it up again then getConstantValue() will return the correct Integer object. Any work around for this?