com.sun.source.tree.NewClassTree Java Examples

The following examples show how to use com.sun.source.tree.NewClassTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConvertToDiamondBulkHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    if (tp.getLeaf().getKind() != Tree.Kind.NEW_CLASS) {
        //XXX: warning
        return ;
    }

    NewClassTree nct = (NewClassTree) tp.getLeaf();

    if (nct.getIdentifier().getKind() != Tree.Kind.PARAMETERIZED_TYPE) {
        //XXX: warning
        return ;
    }

    TreeMaker make = copy.getTreeMaker();
    ParameterizedTypeTree ptt = (ParameterizedTypeTree) nct.getIdentifier();
    ParameterizedTypeTree nue = make.ParameterizedType(ptt.getType(), Collections.<Tree>emptyList());

    copy.rewrite(ptt, nue);
}
 
Example #2
Source File: OWSMPoliciesCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public ExpressionTree createSecurityFeatureInitializer(
        WorkingCopy workingCopy, TreeMaker make, String id )
{
    String clientId = id;
    OWSMPolicyCodeGenerator generator = GENERATORS.get(id);
    if ( generator != null){
        clientId = generator.getClientId();
    }
    if ( !clientId.startsWith( ORACLE )){
        clientId = ORACLE+clientId;
    }
    TypeElement securityType = workingCopy.getElements().getTypeElement(
            SECURITY_POLICY_FEATURE);
    NewClassTree initClassTree = make.NewClass(null, 
            Collections.<ExpressionTree>emptyList(), 
            securityType != null ? make.Identifier( securityType): 
                make.Identifier( SECURITY_POLICY_FEATURE), 
                Collections.singletonList(
                        make.Literal(clientId)), null);
    return make.NewArray(
            createSecurityFeatureComponentType(workingCopy, make ), 
            Collections.<ExpressionTree>emptyList(), 
            Collections.singletonList(initClassTree) );
}
 
Example #3
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Void visitNewClass(NewClassTree node, Void unused) {
    sync(node);
    builder.open(ZERO);
    if (node.getEnclosingExpression() != null) {
        scan(node.getEnclosingExpression(), null);
        builder.breakOp();
        token(".");
    }
    token("new");
    builder.space();
    addTypeArguments(node.getTypeArguments(), plusFour);
    if (node.getClassBody() != null) {
        List<Op> ops = visitModifiers(node.getClassBody().getModifiers(),
                Direction.HORIZONTAL, Optional.<BreakTag>absent());
        builder.addAll(ops);
    }
    scan(node.getIdentifier(), null);
    addArguments(node.getArguments(), plusFour);
    builder.close();
    if (node.getClassBody() != null) {
        addBodyDeclarations(
                node.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    return null;
}
 
Example #4
Source File: StringBufferCharConstructor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath p = ctx.getPath();
    if (p.getLeaf().getKind() != Tree.Kind.NEW_CLASS) {
        return;
    }
    NewClassTree origNct = (NewClassTree)p.getLeaf();
    if (origNct.getArguments().size() != 1) {
        return;
    }
    NewClassTree nct = GeneratorUtilities.get(ctx.getWorkingCopy()).importComments(origNct, ctx.getWorkingCopy().getCompilationUnit());
    ExpressionTree charArg = nct.getArguments().get(0);
    TreeMaker mk = ctx.getWorkingCopy().getTreeMaker();
    
    ExpressionTree newExpr = mk.NewClass(nct.getEnclosingExpression(), (List<ExpressionTree>)nct.getTypeArguments(), nct.getIdentifier(), 
            Collections.<ExpressionTree>emptyList(), nct.getClassBody());

    Tree replace = mk.MethodInvocation(
            Collections.<ExpressionTree>emptyList(), 
            mk.MemberSelect(newExpr, "append"), // NOI18N
            Collections.singletonList(charArg));
    ctx.getWorkingCopy().rewrite(nct, replace);
}
 
Example #5
Source File: CopyFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Boolean visitNewClass(NewClassTree node, TreePath p) {
    if (p == null)
        return super.visitNewClass(node, p);

    NewClassTree t = (NewClassTree) p.getLeaf();

    if (!scan(node.getIdentifier(), t.getIdentifier(), p))
        return false;

    if (!scan(node.getEnclosingExpression(), t.getEnclosingExpression(), p))
        return false;

    if (!checkLists(node.getTypeArguments(), t.getTypeArguments(), p))
        return false;

    if (!checkLists(node.getArguments(), t.getArguments(), p))
        return false;

    return scan(node.getClassBody(), t.getClassBody(), p);
}
 
Example #6
Source File: TreeFinder.java    From annotation-tools with MIT License 6 votes vote down vote up
@Override
public Pair<ASTRecord, Integer> visitNewClass(NewClassTree node, Insertion ins) {
  JCNewClass na = (JCNewClass) node;
  JCExpression className = na.clazz;
  // System.out.printf("classname %s (%s)%n", className, className.getClass());
  while (! (className.getKind() == Tree.Kind.IDENTIFIER)) { // IdentifierTree
    if (className instanceof JCAnnotatedType) {
      className = ((JCAnnotatedType) className).underlyingType;
    } else if (className instanceof JCTypeApply) {
      className = ((JCTypeApply) className).clazz;
    } else if (className instanceof JCFieldAccess) {
      // This occurs for fully qualified names, e.g. "new java.lang.Object()".
      // I'm not quite sure why the field "selected" is taken, but "name" would
      // be a type mismatch. It seems to work, see NewPackage test case.
      className = ((JCFieldAccess) className).selected;
    } else {
      throw new Error(String.format("unrecognized JCNewClass.clazz (%s): %s%n" +
              "   surrounding new class tree: %s%n", className.getClass(), className, node));
    }
    // System.out.printf("classname %s (%s)%n", className, className.getClass());
  }

  return visitIdentifier((IdentifierTree) className, ins);
}
 
Example #7
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAnonymousName() throws Exception {
    doRunTest("package test;\n" +
              "public class Test {\n" +
              "    private Object o = new Object() {};\n" +
              "    private void test() {\n" +
              "        new Object() {\n" +
              "        };" +
              "        final int i = 5;\n" +
              "        ^^\n" +
              "    }" +
              "}",
              "final int j = 5;\n",
              info -> {
                  new TreePathScanner<Void, Void>() {
                      public Void visitNewClass(NewClassTree tree, Void p) {
                          if (getCurrentPath().getParentPath().getLeaf().getKind() == Kind.METHOD) {
                              TypeElement el = (TypeElement) info.getTrees().getElement(new TreePath(getCurrentPath(), tree.getClassBody()));
                              assertEquals("test.Test$2", info.getElements().getBinaryName(el).toString());
                          }
                          return super.visitNewClass(tree, p);
                      }
                  }.scan(info.getCompilationUnit(), null);
              });
}
 
Example #8
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private TreeNode convertNewClass(NewClassTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  ClassInstanceCreation newNode = new ClassInstanceCreation();
  Expression enclosingExpression = (Expression) convert(node.getEnclosingExpression(), path);
  ExecutableElement executable = (ExecutableElement) getElement(path);
  TypeMirror vargarsType = ((JCNewClass) node).varargsElement;
  // Case where the first parameter of the constructor of an inner class is the outer class (e.g.
  // new Outer().new Inner(...). Move the enclosing expression (e.g. new Outer()) as the first
  // argument. A varargs parameter could unintentionally trigger this condition because it could
  // map to zero arguments.
  if (executable.getParameters().size() - node.getArguments().size() == 1
      && vargarsType == null) {
    newNode.addArgument(enclosingExpression);
    enclosingExpression = null;
  }
  for (ExpressionTree arg : node.getArguments()) {
    newNode.addArgument((Expression) convert(arg, path));
  }
  return newNode
      .setExecutablePair(new ExecutablePair(executable))
      .setVarargsType(vargarsType)
      .setExpression(enclosingExpression)
      .setType(convertType(getTypeMirror(getTreePath(path, node.getIdentifier()))))
      .setAnonymousClassDeclaration((TypeDeclaration) convert(node.getClassBody(), path));
}
 
Example #9
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
private void visitEnumConstantDeclaration(VariableTree enumConstant) {
    for (AnnotationTree annotation : enumConstant.getModifiers().getAnnotations()) {
        scan(annotation, null);
        builder.forcedBreak();
    }
    visit(enumConstant.getName());
    NewClassTree init = ((NewClassTree) enumConstant.getInitializer());
    if (init.getArguments().isEmpty()) {
        builder.guessToken("(");
        builder.guessToken(")");
    } else {
        addArguments(init.getArguments(), plusFour);
    }
    if (init.getClassBody() != null) {
        addBodyDeclarations(
                init.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
}
 
Example #10
Source File: FieldTest1.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * copy the initialization 'new String("NetBeers")' to 'new String()'.
 * It tests only change in expression, no expression swap.
 */
public void testFieldChangeInInitValue() throws IOException {
    System.err.println("testFieldChangeInInitValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueReplacer".contentEquals(node.getName())) {
                    if (Tree.Kind.NEW_CLASS.equals(node.getInitializer().getKind())) {
                        NewClassTree nct = (NewClassTree) node.getInitializer();
                        NewClassTree njuNct = make.NewClass(
                                nct.getEnclosingExpression(), 
                                (List<ExpressionTree>) nct.getTypeArguments(),
                                nct.getIdentifier(),
                                Collections.singletonList(make.Literal("NetBeans")),
                                nct.getClassBody()
                        );
                        copy.rewrite(nct, njuNct);
                    }
                }
                return null;
            }
        }
    );
    assertFiles("testFieldChangeInInitValue.pass");
}
 
Example #11
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapMethod1() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFound, java.net.MalformedURLException { } }", new SourcePositions[1]);
            parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed);
            MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
        }
    },
    FmtOptions.wrapMethodParams, WrapStyle.WRAP_IF_LONG.name(),
    FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_IF_LONG.name(),
    FmtOptions.wrapThrowsList, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #12
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitNewClass(NewClassTree node, Void unused) {
    sync(node);
    builder.open(ZERO);
    if (node.getEnclosingExpression() != null) {
        scan(node.getEnclosingExpression(), null);
        builder.breakOp();
        token(".");
    }
    token("new");
    builder.space();
    addTypeArguments(node.getTypeArguments(), plusFour);
    if (node.getClassBody() != null) {
        List<Op> ops = visitModifiers(node.getClassBody().getModifiers(),
                Direction.HORIZONTAL, Optional.<BreakTag>absent());
        builder.addAll(ops);
    }
    scan(node.getIdentifier(), null);
    addArguments(node.getArguments(), plusFour);
    builder.close();
    if (node.getClassBody() != null) {
        addBodyDeclarations(
                node.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    return null;
}
 
Example #13
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapMethod2() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFoundException, java.net.MalformedURLException { } }", new SourcePositions[1]);
            parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed);
            MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
        }
    },
    FmtOptions.wrapMethodParams, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsList, WrapStyle.WRAP_ALWAYS.name());
}
 
Example #14
Source File: ConvertToLambda.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern("new $clazz($params$) { $method; }") //NOI18N
})
@NbBundle.Messages("MSG_AnonymousConvertibleToLambda=This anonymous inner class creation can be turned into a lambda expression.")
public static ErrorDescription computeAnnonymousToLambda(HintContext ctx) {
    ClassTree clazz = ((NewClassTree) ctx.getPath().getLeaf()).getClassBody();
    ConvertToLambdaPreconditionChecker preconditionChecker =
            new ConvertToLambdaPreconditionChecker(ctx.getPath(), ctx.getInfo());
    if (!preconditionChecker.passesFatalPreconditions()) {
        return null;
    }

    FixImpl fix = new FixImpl(ctx.getInfo(), ctx.getPath(), false);
    if (ctx.getPreferences().getBoolean(KEY_PREFER_MEMBER_REFERENCES, DEF_PREFER_MEMBER_REFERENCES)
            && (preconditionChecker.foundMemberReferenceCandidate() || preconditionChecker.foundConstructorReferenceCandidate())) {
        return ErrorDescriptionFactory.forTree(ctx, ((NewClassTree) ctx.getPath().getLeaf()).getIdentifier(), Bundle.MSG_AnonymousConvertibleToLambda(),
                new FixImpl(ctx.getInfo(), ctx.getPath(), true).toEditorFix(), fix.toEditorFix());
    }
    return ErrorDescriptionFactory.forTree(ctx, ((NewClassTree) ctx.getPath().getLeaf()).getIdentifier(), 
            Bundle.MSG_AnonymousConvertibleToLambda(), fix.toEditorFix());
}
 
Example #15
Source File: InstanceRefFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object visitNewClass(NewClassTree node, Object p) {
    Element e = ci.getTrees().getElement(getCurrentPath());
    if (e != null && e.getKind() == ElementKind.CONSTRUCTOR) {
        addInstanceForConstructor(e);
    }
    Object r = scan(node.getEnclosingExpression(), p);
    r = scanAndReduce(node.getIdentifier(), p, r);
    r = scanAndReduce(node.getTypeArguments(), p, r);
    r = scanAndReduce(node.getArguments(), p, r);
    
    // switch context to the anonymous class
    if (e != null) {
        TypeElement saveType = enclosingType;
        enclosingType = ci.getElementUtilities().enclosingTypeElement(e);
        r = scanAndReduce(node.getClassBody(), p, r);
        this.enclosingType = saveType;
    }
    return r;
}
 
Example #16
Source File: FindLocalUsagesQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitNewClass(NewClassTree node, Stack<Tree> p) {
    if (instantRename) {
        return super.visitNewClass(node, p);
    }
    
    Element el = info.getTrees().getElement(getCurrentPath());

    if (toFind.equals(el) && node.getIdentifier() != null) {
        Token<JavaTokenId> t = Utilities.getToken(info, doc, new TreePath(getCurrentPath(), node.getIdentifier()));
        
        if (t != null)
            usages.add(t);

        return null;
    }

    if (el != null && toFind.equals(el.getEnclosingElement())) {
        return null;
    }
    
    return super.visitNewClass(node, p);
}
 
Example #17
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitNewClass(NewClassTree node, Trees p) {
    Tree t = super.visitNewClass(node, p);
    // new class tree > expression statement tree > block. Does not accept anonymous classes for ctor references.
    if (node.getClassBody() == null && singleStatementLambdaMethodBody == getCurrentPath().getParentPath().getParentPath().getLeaf()) {
        Tree parent = getCurrentPath().getParentPath().getLeaf();
        Element el = info.getTrees().getElement(getCurrentPath());
        if (el == null || el.getKind() != ElementKind.CONSTRUCTOR || !el.getEnclosingElement().getKind().isClass()) {
            return t;
        }
        el = el.getEnclosingElement();
        if (parent.getKind() == Tree.Kind.EXPRESSION_STATEMENT || parent.getKind() == Tree.Kind.RETURN) {
            ExpressionTree et = node.getEnclosingExpression();
            if (et != null) {
                if (el.getModifiers().contains(Modifier.STATIC) || !isMeaninglessQualifier(new TreePath(getCurrentPath().getParentPath(), et))) {
                    return t;
                }
            }
            foundConstructorReferenceCandidate = true;
        }
    }
    return t;
}
 
Example #18
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a method or constructor call would become ambiguous if the parameter type changes.
 * 
 * @param info compilation context
 * @param parentExec path to the constructor or method invocation
 * @param argIndex
 * @param casteeType
 * @return 
 */
private static boolean checkAmbiguous(CompilationInfo info, final TreePath parentExec, int argIndex, TypeMirror casteeType, TreePath realArgTree) {
    CharSequence altType = info.getTypeUtilities().getTypeName(casteeType, TypeUtilities.TypeNameOptions.PRINT_FQN);
    String prefix = null;
    if (casteeType != null && !(casteeType.getKind() == TypeKind.NULL || casteeType.getKind() == TypeKind.INTERSECTION)) {
        prefix = "(" + altType + ")"; // NOI18N
    }
    Tree leaf = parentExec.getLeaf();
    List<? extends Tree> arguments;
    if (leaf instanceof MethodInvocationTree) {
        MethodInvocationTree mi = (MethodInvocationTree)leaf;
        arguments = mi.getArguments();
    } else {
        arguments = ((NewClassTree)leaf).getArguments();
    }
    Tree argTree = arguments.get(argIndex);
    TreePath argPath = new TreePath(parentExec, argTree);
    return !Utilities.checkAlternativeInvocation(info, parentExec, argPath, realArgTree, prefix);
}
 
Example #19
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public List<? extends TypeMirror> visitNewClass(NewClassTree node, Object p) {
    TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
    if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        return null;
    }
    Element el = info.getTrees().getElement(getCurrentPath());
    if (el == null) {
        return null;
    }
    if (theExpression.getLeaf() != node.getEnclosingExpression()) {
        ExecutableType execType = (ExecutableType)info.getTypes().asMemberOf((DeclaredType)tm, el);
        return visitMethodOrNew(node, p, node.getArguments(), execType);
    } else {
        DeclaredType dt = (DeclaredType)tm;
        if (dt.getEnclosingType() == null) {
            return null;
        }
        return Collections.singletonList(dt.getEnclosingType());
    }
}
 
Example #20
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to resolve a method or a constructor call with an altered argument tree.
 * 
 * @param ci the context
 * @param invPath path to the method invocation node
 * @param origPath path to the Tree within method's arguments which should be replaced
 * @param valPath the replacement tree
 * @return 
 */
public static boolean checkAlternativeInvocation(CompilationInfo ci, TreePath invPath, 
        TreePath origPath,
        TreePath valPath, String customPrefix) {
    Tree l = invPath.getLeaf();
    Tree sel;
    
    if (l.getKind() == Tree.Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree)invPath.getLeaf();
        sel = nct.getIdentifier();
    } else if (l.getKind() == Tree.Kind.METHOD_INVOCATION) {
        MethodInvocationTree mit = (MethodInvocationTree)invPath.getLeaf();
        sel = mit.getMethodSelect();
    } else {
        return false;
    }
    
    return resolveAlternativeInvocation(ci, invPath, 
            origPath, sel, valPath, customPrefix);
}
 
Example #21
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected boolean generateClassBody(TreePath p) throws Exception {
    Element e = copy.getTrees().getElement(p);
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    if (isUsableElement) {
        return true;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        VariableTree var = (VariableTree) p.getLeaf();
        if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) var.getInitializer();
            if (nct.getClassBody() != null) {
                return true;
            }
        }
    }
    return !generateClassBody2(copy, p);
}
 
Example #22
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
  if (methodSymbol == null) {
    throw new RuntimeException("not expecting unresolved method here");
  }
  List<? extends ExpressionTree> actualParams = tree.getArguments();
  if (tree.getClassBody() != null && actualParams.size() > 0) {
    // passing parameters to constructor of anonymous class
    // this constructor just invokes the constructor of the superclass, and
    // in the AST does not have the parameter nullability annotations from the superclass.
    // so, treat as if the superclass constructor is being invoked directly
    // see https://github.com/uber/NullAway/issues/102
    methodSymbol = getSymbolOfSuperConstructor(methodSymbol, state);
  }
  return handleInvocation(tree, state, methodSymbol, actualParams);
}
 
Example #23
Source File: ClassMetrics.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(
    displayName = "#DN_AnonClassMethodCount",
    description = "#DESC_AnonClassMethodCount",
    category = "metrics",
    options = { Hint.Options.HEAVY, Hint.Options.QUERY },
    enabled = false
)
@TriggerPatterns({
    @TriggerPattern("new $classname<$tparams$>($params$) { $members$; }"),
    @TriggerPattern("$expr.new $classname<$tparams$>($params$) { $members$; }"),
    @TriggerPattern("new $classname($params$) { $members$; }"),
    @TriggerPattern("$expr.new $classname($params$) { $members$; }"),
})
@UseOptions({ OPTION_ANON_CLASS_METHODS_LIMIT})
public static ErrorDescription anonymousTooManyMethods(HintContext ctx) {
    NewClassTree nct = (NewClassTree)ctx.getPath().getLeaf();

    return checkTooManyMethods(ctx, 
        new TreePath(ctx.getPath(), nct.getClassBody()),
        ctx.getPreferences().getInt(OPTION_ANON_CLASS_METHODS_LIMIT, DEFAULT_ANON_CLASS_METHODS_LIMIT),
        true);
}
 
Example #24
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
private void visitEnumConstantDeclaration(VariableTree enumConstant) {
  for (AnnotationTree annotation : enumConstant.getModifiers().getAnnotations()) {
    scan(annotation, null);
    builder.forcedBreak();
  }
  visit(enumConstant.getName());
  NewClassTree init = ((NewClassTree) enumConstant.getInitializer());
  if (init.getArguments().isEmpty()) {
    builder.guessToken("(");
    builder.guessToken(")");
  } else {
    addArguments(init.getArguments(), plusFour);
  }
  if (init.getClassBody() != null) {
    addBodyDeclarations(
        init.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
  }
}
 
Example #25
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Element which is incomplete, or, for anonymous classes, 
 * returns the extended TypeElement (which is also incomplete). This is because
 * an Element is not available for the incomplete class.
 */
private static TypeElement findTypeElement(CompilationInfo info, TreePath path) {
    Element e = info.getTrees().getElement(path);
    if (e == null) {
        return null;
    } else if (e.getKind().isClass() || e.getKind().isInterface()) {
        return (TypeElement)e;
    }
    TypeMirror tm = info.getTrees().getTypeMirror(path);
    if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        if (path.getLeaf().getKind() == Tree.Kind.NEW_CLASS) {
            tm = info.getTrees().getTypeMirror(new TreePath(path, ((NewClassTree)path.getLeaf()).getIdentifier()));
        }
    }
    if (tm != null && tm.getKind() == TypeKind.DECLARED) {
        return (TypeElement)((DeclaredType)tm).asElement();
    } else {
        return null;
    }
}
 
Example #26
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ConvertToLambdaPreconditionChecker(TreePath pathToNewClassTree, CompilationInfo info) {

        this.pathToNewClassTree = pathToNewClassTree;
        this.newClassTree = (NewClassTree) pathToNewClassTree.getLeaf();
        this.info = info;
        this.types = info.getTypes();

        Element el = info.getTrees().getElement(pathToNewClassTree);
        if (el != null && el.getKind() == ElementKind.CONSTRUCTOR) {
            createdClass = el.getEnclosingElement();
        } else {
            createdClass = null;
        }
        this.lambdaMethodTree = getMethodFromFunctionalInterface(this.pathToNewClassTree);
        this.localScope = getScopeFromTree(this.pathToNewClassTree);
        this.ownerClass = findFieldOwner();
    }
 
Example #27
Source File: SideEffectVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object visitNewClass(NewClassTree node, Object p) {
    Element e = ctx.getInfo().getTrees().getElement(getCurrentPath());
    if (e == null) {
        return super.visitNewClass(node, p);
    } else {
        e = e.getEnclosingElement();
    }
    if (e != null && e.getKind().isClass()) {
        Object r = scan(node.getEnclosingExpression(), p);
        r = scanAndReduce(node.getIdentifier(), p, r);
        r = scanAndReduce(node.getTypeArguments(), p, r);
        r = scanAndReduce(node.getArguments(), p, r);
        nestingLevel++;
        enclosingElements.push((TypeElement) e);
        r = scanAndReduce(node.getClassBody(), p, r);
        nestingLevel--;
        enclosingElements.pop();
        return r;
    } else {
        return super.visitNewClass(node, p);
    }
}
 
Example #28
Source File: ReplaceBufferByString.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitNewClass(NewClassTree node, Void p) {
    scan(node.getEnclosingExpression(), p);
    for (ExpressionTree et : node.getArguments()) {
        Boolean used = scan(et, p);
        if (used == Boolean.TRUE) {
            passedToMethod = true;
        }
    }
    return false;
}
 
Example #29
Source File: ScanStatement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitNewClass(NewClassTree node, Void p) {
    nesting++;
    super.visitNewClass(node, p);
    nesting--;
    return null;
}
 
Example #30
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public CodeModel visitNewClass(NewClassTree node, VisitContext context) {
  ClassModel identifier = (ClassModel) scan(node.getIdentifier(), context);
  List<ExpressionModel> arguments = node.getArguments().stream().map(arg -> scan(arg, context)).collect(Collectors.toList());
  JCTree.JCNewClass newClass = (JCTree.JCNewClass) node;
  return identifier.onNew(arguments);
}