Esempio n. 1
0
  /**
   * Adds the given new method declaration to the provided type AST Node. Can also inject
   * constructors.
   *
   * <p>Also takes care of updating the JavacAST.
   */
  public static void injectMethod(JavacNode typeNode, JCMethodDecl method) {
    JCClassDecl type = (JCClassDecl) typeNode.get();

    if (method.getName().contentEquals("<init>")) {
      // Scan for default constructor, and remove it.
      int idx = 0;
      for (JCTree def : type.defs) {
        if (def instanceof JCMethodDecl) {
          if ((((JCMethodDecl) def).mods.flags & Flags.GENERATEDCONSTR) != 0) {
            JavacNode tossMe = typeNode.getNodeFor(def);
            if (tossMe != null) tossMe.up().removeChild(tossMe);
            type.defs = addAllButOne(type.defs, idx);
            if (type.sym != null && type.sym.members_field != null) {
              type.sym.members_field.remove(((JCMethodDecl) def).sym);
            }
            break;
          }
        }
        idx++;
      }
    }

    addSuppressWarningsAll(method.mods, typeNode, method.pos, getGeneratedBy(method));
    type.defs = type.defs.append(method);

    typeNode.add(method, Kind.METHOD);
  }
Esempio n. 2
0
  private static void injectField(
      JavacNode typeNode, JCVariableDecl field, boolean addSuppressWarnings) {
    JCClassDecl type = (JCClassDecl) typeNode.get();

    if (addSuppressWarnings)
      addSuppressWarningsAll(field.mods, typeNode, field.pos, getGeneratedBy(field));

    List<JCTree> insertAfter = null;
    List<JCTree> insertBefore = type.defs;
    while (insertBefore.tail != null) {
      if (insertBefore.head instanceof JCVariableDecl) {
        JCVariableDecl f = (JCVariableDecl) insertBefore.head;
        if (isEnumConstant(f) || isGenerated(f)) {
          insertAfter = insertBefore;
          insertBefore = insertBefore.tail;
          continue;
        }
      }
      break;
    }
    List<JCTree> fieldEntry = List.<JCTree>of(field);
    fieldEntry.tail = insertBefore;
    if (insertAfter == null) {
      type.defs = fieldEntry;
    } else {
      insertAfter.tail = fieldEntry;
    }

    typeNode.add(field, Kind.FIELD);
  }