Пример #1
0
  /**
   * Generates code to convert a wrapped value type to a primitive type. Handles unwrapping
   * java.lang.Boolean, and java.lang.Number types. Generates the appropriate RETURN bytecode.
   */
  static void generateReturnResult(
      ClassFileWriter cfw, Class<?> retType, boolean callConvertResult) {
    // wrap boolean values with java.lang.Boolean, convert all other
    // primitive values to java.lang.Double.
    if (retType == Void.TYPE) {
      cfw.add(ByteCode.POP);
      cfw.add(ByteCode.RETURN);

    } else if (retType == Boolean.TYPE) {
      cfw.addInvoke(
          ByteCode.INVOKESTATIC, "aurora/javascript/Context", "toBoolean", "(Ljava/lang/Object;)Z");
      cfw.add(ByteCode.IRETURN);

    } else if (retType == Character.TYPE) {
      // characters are represented as strings in JavaScript.
      // return the first character.
      // first convert the value to a string if possible.
      cfw.addInvoke(
          ByteCode.INVOKESTATIC,
          "aurora/javascript/Context",
          "toString",
          "(Ljava/lang/Object;)Ljava/lang/String;");
      cfw.add(ByteCode.ICONST_0);
      cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "charAt", "(I)C");
      cfw.add(ByteCode.IRETURN);

    } else if (retType.isPrimitive()) {
      cfw.addInvoke(
          ByteCode.INVOKESTATIC, "aurora/javascript/Context", "toNumber", "(Ljava/lang/Object;)D");
      String typeName = retType.getName();
      switch (typeName.charAt(0)) {
        case 'b':
        case 's':
        case 'i':
          cfw.add(ByteCode.D2I);
          cfw.add(ByteCode.IRETURN);
          break;
        case 'l':
          cfw.add(ByteCode.D2L);
          cfw.add(ByteCode.LRETURN);
          break;
        case 'f':
          cfw.add(ByteCode.D2F);
          cfw.add(ByteCode.FRETURN);
          break;
        case 'd':
          cfw.add(ByteCode.DRETURN);
          break;
        default:
          throw new RuntimeException("Unexpected return type " + retType.toString());
      }

    } else {
      String retTypeStr = retType.getName();
      if (callConvertResult) {
        cfw.addLoadConstant(retTypeStr);
        cfw.addInvoke(
            ByteCode.INVOKESTATIC,
            "java/lang/Class",
            "forName",
            "(Ljava/lang/String;)Ljava/lang/Class;");

        cfw.addInvoke(
            ByteCode.INVOKESTATIC,
            "aurora/javascript/JavaAdapter",
            "convertResult",
            "(Ljava/lang/Object;" + "Ljava/lang/Class;" + ")Ljava/lang/Object;");
      }
      // Now cast to return type
      cfw.add(ByteCode.CHECKCAST, retTypeStr);
      cfw.add(ByteCode.ARETURN);
    }
  }