Example usage for org.eclipse.jdt.core.dom MethodDeclaration setConstructor

List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration setConstructor

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom MethodDeclaration setConstructor.

Prototype

public void setConstructor(boolean isConstructor) 

Source Link

Document

Sets whether this declaration declares a constructor or a method.

Usage

From source file:br.com.objectos.way.core.code.jdt.TypeDeclarationWriter.java

License:Apache License

public MethodDeclarationWriter addConstructor() {
    MethodDeclaration method = ast.newMethodDeclaration();
    method.setConstructor(true);
    type.bodyDeclarations().add(method);

    SimpleName name = type.getName();//from  w w w  .ja v  a2 s  .  com
    method.setName(ast.newSimpleName(name.getIdentifier()));

    return new MethodDeclarationWriter(method);
}

From source file:ch.acanda.eclipse.pmd.java.resolution.design.UseUtilityClassQuickFix.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) {
    final AST ast = typeDeclaration.getAST();
    final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class);
    constructor.setConstructor(true);

    final Modifier modifier = (Modifier) ast.createInstance(Modifier.class);
    modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD);
    constructor.modifiers().add(modifier);

    constructor.setName(ASTUtil.copy(typeDeclaration.getName()));

    final Block body = (Block) ast.createInstance(Block.class);
    constructor.setBody(body);//from  w w  w . j  a va 2 s .  c  o  m

    final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
    final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class",
            ASTNode.EMPTY_STATEMENT);
    statementRewrite.insertFirst(comment, null);

    final int position = findConstructorPosition(typeDeclaration);
    final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration,
            TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
    bodyDeclarationRewrite.insertAt(constructor, position, null);
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaClass_OwnedMethods.java

License:Open Source License

/**
 * @author Luiza - conditions for interface and abstract methods added
 * @flowerModelElementId _zbW4iZiOEd6aNMdNFvR5WQ
 *///from  ww w  . ja  v  a  2s  .  c  o m
@SuppressWarnings("unchecked")
@Override
protected MethodDeclaration createAndAddNewASTElement(Operation modelElement,
        CompilationUnit parentAstElement) {
    TypeDeclaration parentClass = JavaSyncUtils.getMasterClass((CompilationUnit) parentAstElement);
    AST ast = parentClass.getAST();
    MethodDeclaration method = ast.newMethodDeclaration();
    if (modelElement.getName().equals(parentClass.getName().getIdentifier())) {
        //create a constructor
        method.setConstructor(true);
    }
    parentClass.bodyDeclarations().add(method);

    //if this method is not in an interface and is not an abstract method then add a body
    if (!JavaSyncUtils.getMasterClass(parentAstElement).isInterface() && !modelElement.isAbstract()) {
        Block methodBlock = ast.newBlock();
        method.setBody(methodBlock);
    }
    return method;
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaMethod.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w w  w . j  ava  2  s  .  c  om
protected void setASTFeatureValue(EStructuralFeature feature, MethodDeclaration astElement, Object value)
        throws CodeSyncException {
    if (astElement == null)
        throw new IllegalArgumentException("astElement null ");
    AST ast = astElement.getAST();

    switch (feature.getFeatureID()) {
    case UMLPackage.NAMED_ELEMENT__NAME:
        if (value == null)
            throw new IllegalArgumentException("setting name to null value ");
        astElement.setName(ast.newSimpleName((String) value));
        break;
    case UMLPackage.OPERATION__TYPE:
        parentForwardJavaClass_OwnedMethods.parentForwardJavaType.parentForwardJavaSrcDir_Files
                .createImportDeclarationIfNeeded((Type) value);
        String modelReturnType = value == null ? null : ((Type) value).getName();
        if (!astElement.isConstructor()) {
            TypeDeclaration parent = (TypeDeclaration) astElement.getParent();
            if (value == null
                    && astElement.getName().getIdentifier().equals(parent.getName().getIdentifier())) {
                // transform this method to constructor
                astElement.setConstructor(true);
            } else //if null value => return void type
                astElement.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, modelReturnType, true));
        } else if (value != null) {
            // transforming from constructor to ordinary method
            astElement.setConstructor(false);
            astElement.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, modelReturnType, true));
        }
        break;
    case UMLPackage.BEHAVIORAL_FEATURE__OWNED_PARAMETER:
        astElement.parameters().clear();
        for (Parameter par : (List<Parameter>) value)
            if (par.getDirection().equals(ParameterDirectionKind.IN_LITERAL)) {
                parentForwardJavaClass_OwnedMethods.parentForwardJavaType.parentForwardJavaSrcDir_Files
                        .createImportDeclarationIfNeeded(par.getType());

                SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
                String paramName = par.getName();
                String paramType = par.getType() == null ? null : par.getType().getName();
                if (paramName == null)
                    throw new IllegalArgumentException("Parameter name is null: " + par);
                variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, paramType, true));
                try {
                    variableDeclaration.setName(ast.newSimpleName(paramName));
                } catch (IllegalArgumentException e) {
                    throw new CodeSyncException("Invalid Parameter Name: \"" + paramName
                            + "\" on java operation: " + astElement.getName() + "()", e);
                }
                astElement.parameters().add(variableDeclaration);
            }
        break;
    case UMLPackage.BEHAVIORAL_FEATURE__IS_ABSTRACT:
        JavaSyncUtils.updateModifierFromModelToJavaClass(astElement, (Boolean) value,
                JavaSyncUtils.MODIFIER_ABSTRACT);
        break;
    case UMLPackage.ELEMENT__EANNOTATIONS:
        List<EAnnotation> annotations = (List<EAnnotation>) value;
        for (EAnnotation annot : annotations) {
            // search for a template method annotation
            if (annot.getSource().equals("TemplateMethod") && annot.getDetails().containsKey("id")) {
                String bodyContent = JetTemplateFactory.INSTANCE
                        .invokeOperationJetTemplate(annot.getEModelElement(), annot.getDetails().get("id"));
                if (annot.getDetails().containsKey("comment")) { // if it must contain also the template comment
                    String commentLine = JetTemplateFactory.INSTANCE.invokeOperationJetTemplate(
                            annot.getEModelElement(), annot.getDetails().get("comment"));
                    JavaSyncUtils.generateBodyWithCommentForMethod(astElement, bodyContent, commentLine);
                } else { // add only content to method
                    JavaSyncUtils.generateBodyForMethod(astElement, bodyContent);
                }
                // remove annotation; it doesn't need to be synchronized
                annotations.remove(annot);
                break;
            }
        }
        break;
    default:
        super.setASTFeatureValue(feature, astElement, value);
    }
}

From source file:com.google.devtools.j2cpp.translate.AnonymousClassConverter.java

License:Open Source License

/**
 * Adds val$N instance fields to type so references to external
 * variables can be resolved.  Existing constructors are updated to
 * initialize these fields; if no constructor exists, one is added.
 *///from   w w w  .  j  a va 2 s .co  m
private GeneratedMethodBinding addInnerVars(TypeDeclaration node, List<IVariableBinding> innerVars,
        List<ReferenceDescription> references, List<Expression> invocationArguments) {
    @SuppressWarnings("unchecked")
    List<BodyDeclaration> members = node.bodyDeclarations(); // safe by definition
    List<IVariableBinding> innerFields = Lists.newArrayList();
    AST ast = node.getAST();
    ITypeBinding clazz = Types.getTypeBinding(node);

    for (IVariableBinding var : innerVars) {
        if (!isConstant(var)) { // Constants are in-lined instead.
            ITypeBinding varType = var.getDeclaringClass();
            if (varType == null) {
                varType = var.getType();
            }
            if (Types.hasIOSEquivalent(varType)) {
                varType = Types.mapType(varType);
            }
            String fieldName = "val$" + var.getName();
            FieldDeclaration field = createField(fieldName, varType, clazz, ast);
            members.add(field);
            IVariableBinding fieldVar = Types.getVariableBinding(field.fragments().get(0));
            innerFields.add(fieldVar);
            for (ReferenceDescription ref : references) {
                if (ref.binding == var && ref.innerField == null) {
                    ref.innerField = fieldVar;
                }
            }
        }
    }

    // Insert new parameters into constructor, if one was added by the
    // InitializationNormalizer from initializer blocks.
    boolean needsConstructor = true;
    GeneratedMethodBinding defaultConstructor = null;
    List<MethodDeclaration> enumConstructors = Lists.newArrayList();
    ITypeBinding enclosingClass = clazz.getDeclaringClass();
    for (BodyDeclaration member : members) {
        if (member instanceof MethodDeclaration && ((MethodDeclaration) member).isConstructor()) {
            if (argsMatch(invocationArguments, Types.getMethodBinding(member).getParameterTypes())) {
                MethodDeclaration constructor = (MethodDeclaration) member;
                needsConstructor = false;
                IMethodBinding oldBinding = Types.getMethodBinding(constructor);
                GeneratedMethodBinding newBinding = new GeneratedMethodBinding(oldBinding);
                Types.addBinding(constructor, newBinding);
                addInnerParameters(constructor, newBinding, innerFields, ast, true);
                defaultConstructor = newBinding;
                Symbols.scanAST(constructor);
                assert constructor.parameters().size() == defaultConstructor.getParameterTypes().length;
            }
            if (enclosingClass.isEnum()) {
                enumConstructors.add((MethodDeclaration) member);
            }
        }
    }

    if (!enumConstructors.isEmpty()) {
        for (MethodDeclaration constructor : enumConstructors) {
            GeneratedMethodBinding binding = new GeneratedMethodBinding(Types.getMethodBinding(constructor));
            if (!invocationArguments.isEmpty()) {
                // Remove super invocation added by InitializationNormalizer.
                @SuppressWarnings("unchecked")
                List<Statement> stmts = constructor.getBody().statements(); // safe by definition
                for (int i = 0; i < stmts.size(); i++) {
                    if (stmts.get(i) instanceof SuperConstructorInvocation) {
                        stmts.remove(i);
                        break;
                    }
                }

                // Update the binding to include the arguments,
                addArguments(invocationArguments, ast, clazz, constructor, binding);
                addInnerParameters(constructor, binding, innerFields, ast, true);
                Symbols.scanAST(constructor);
                Types.addBinding(constructor, binding);
            } else {
                defaultConstructor = binding;
            }
        }
        if (defaultConstructor == null) {
            defaultConstructor = new GeneratedMethodBinding(Types.getMethodBinding(enumConstructors.get(0)));
        }
    } else if (needsConstructor) {
        MethodDeclaration constructor = ast.newMethodDeclaration();
        constructor.setConstructor(true);
        ITypeBinding voidType = ast.resolveWellKnownType("void");
        GeneratedMethodBinding binding = new GeneratedMethodBinding("init", 0, voidType, clazz, true, false,
                true);
        Types.addBinding(constructor, binding);
        Types.addBinding(constructor.getReturnType2(), voidType);
        SimpleName name = ast.newSimpleName("init");
        Types.addBinding(name, binding);
        constructor.setName(name);
        constructor.setBody(ast.newBlock());
        if (!invocationArguments.isEmpty()) {
            addArguments(invocationArguments, ast, clazz, constructor, binding);
        }
        addInnerParameters(constructor, binding, innerFields, ast, true);
        members.add(constructor);
        Symbols.scanAST(constructor);
        defaultConstructor = binding;
        assert constructor.parameters().size() == defaultConstructor.getParameterTypes().length;
    }

    assert defaultConstructor != null;
    return defaultConstructor;
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Adds a nullary constructor that invokes a superclass constructor with
 * default arguments.//from  ww w.ja va 2 s . com
 */
@SuppressWarnings("unchecked")
private void generateConstructor(TypeDeclaration node) {
    ITypeBinding clazz = node.resolveBinding();
    IMethodBinding superConstructor = getVisible(getConstructors(clazz.getSuperclass())).next();

    // Add an explicit constructor that calls super with suitable default arguments.
    AST ast = node.getAST();
    MethodDeclaration constructor = ast.newMethodDeclaration();
    constructor.setConstructor(true);
    constructor.setName(ast.newSimpleName(node.getName().getIdentifier()));
    constructor.modifiers().add(ast.newModifier(ModifierKeyword.PROTECTED_KEYWORD));
    node.bodyDeclarations().add(constructor);

    Block block = ast.newBlock();
    constructor.setBody(block);
    SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
    block.statements().add(invocation);
    addAssertionError(block);

    for (ITypeBinding type : superConstructor.getParameterTypes()) {
        Expression value = getDefaultValue(ast, type);
        CastExpression cast = ast.newCastExpression();
        cast.setExpression(value);
        cast.setType(createType(ast, clazz, type));
        invocation.arguments().add(cast);
    }
}

From source file:com.google.devtools.j2cpp.translate.InitializationNormalizer.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addMethod(String name, int modifiers, ITypeBinding type, List<Statement> initStatements,
        List<BodyDeclaration> members, AST ast, boolean isConstructor) {
    Block body = ast.newBlock();/*from  w w w  .ja va2s.c  o  m*/
    List<Statement> stmts = body.statements(); // safe by definition
    for (Statement stmt : initStatements) {
        Statement newStmt = NodeCopier.copySubtree(ast, stmt);
        stmts.add(newStmt);
    }
    MethodDeclaration method = ast.newMethodDeclaration();
    GeneratedMethodBinding binding = new GeneratedMethodBinding(name, modifiers, null, type, isConstructor,
            false, true);
    Types.addBinding(method, binding);
    Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    Types.addBinding(returnType, ast.resolveWellKnownType("void"));
    method.setReturnType2(returnType);
    method.setBody(body);
    method.setConstructor(isConstructor);
    method.modifiers().addAll(ast.newModifiers(modifiers));
    SimpleName nameNode = NameTable.unsafeSimpleName(name, ast);
    Types.addBinding(nameNode, binding);
    method.setName(nameNode);
    members.add(method);
    Symbols.resolve(method, binding);
}

From source file:com.google.devtools.j2cpp.translate.InnerClassExtractor.java

License:Open Source License

private void addOuterFields(AbstractTypeDeclaration node) {
    @SuppressWarnings("unchecked")
    List<BodyDeclaration> members = node.bodyDeclarations(); // safe by definition
    AST ast = node.getAST();/*from w w  w.  ja  v  a 2  s . c  o m*/
    ITypeBinding clazz = Types.getTypeBinding(node);
    ITypeBinding outerClazz = clazz.getDeclaringClass();
    assert outerClazz != null;

    List<IVariableBinding> innerFields = Lists.newArrayList();
    // Ensure that the new outer field does not conflict with a field in a superclass.
    ITypeBinding superClazz = clazz.getSuperclass();
    ITypeBinding superDeclaringClazz = superClazz.getDeclaringClass();
    int suffix = 0;
    while (superClazz.getDeclaringClass() != null) {
        if (!Modifier.isStatic(superClazz.getModifiers())) {
            suffix++;
        }
        superClazz = superClazz.getSuperclass();
    }
    String outerFieldName = "this$" + suffix;

    FieldDeclaration outerField = createField(outerFieldName, outerClazz, clazz, ast);
    members.add(0, outerField);
    IVariableBinding outerVar = Types.getVariableBinding(outerField.fragments().get(0));
    innerFields.add(outerVar);

    if (superDeclaringClazz != null && !Modifier.isStatic(clazz.getSuperclass().getModifiers())
            && !outerClazz.isAssignmentCompatible(superDeclaringClazz.getTypeDeclaration())) {
        // The super class is an inner class, and it's declaring class and the
        // current node's declaring class don't match, so we need another outer
        // var. This var is only a parameter, not a field, an it's name doesn't
        // matter because addInnerParameters will assign a different name to it
        // anyway.
        IVariableBinding secondOuterVar = new GeneratedVariableBinding("", Modifier.FINAL, superDeclaringClazz,
                false, true, superClazz, null);
        innerFields.add(secondOuterVar);
    }

    // Insert new parameters for each constructor in class.
    boolean needsConstructor = true;
    for (BodyDeclaration member : members) {
        if (member instanceof MethodDeclaration && ((MethodDeclaration) member).isConstructor()) {
            needsConstructor = false;
            MethodDeclaration constructor = (MethodDeclaration) member;
            IMethodBinding oldBinding = Types.getMethodBinding(constructor);
            GeneratedMethodBinding newBinding = new GeneratedMethodBinding(oldBinding);
            Types.addBinding(constructor, newBinding);
            addInnerParameters(constructor, newBinding, innerFields, ast, false);
            assert constructor.parameters().size() == newBinding.getParameterTypes().length;
        }
    }

    if (needsConstructor) {
        MethodDeclaration constructor = ast.newMethodDeclaration();
        constructor.setConstructor(true);
        ITypeBinding voidType = ast.resolveWellKnownType("void");
        GeneratedMethodBinding binding = new GeneratedMethodBinding("init", 0, voidType, clazz, true, false,
                true);
        Types.addBinding(constructor, binding);
        Types.addBinding(constructor.getReturnType2(), voidType);
        SimpleName name = ast.newSimpleName("init");
        Types.addBinding(name, binding);
        constructor.setName(name);
        constructor.setBody(ast.newBlock());
        addInnerParameters(constructor, binding, innerFields, ast, false);
        members.add(constructor);
        assert constructor.parameters().size() == binding.getParameterTypes().length;
    }
}

From source file:com.google.devtools.j2objc.translate.ASTFactory.java

License:Apache License

public static MethodDeclaration newMethodDeclaration(AST ast, IMethodBinding binding) {
    MethodDeclaration declaration = ast.newMethodDeclaration();
    declaration.setConstructor(binding.isConstructor());
    declaration.setName(newSimpleName(ast, binding));
    declaration.setReturnType2(newType(ast, binding.getReturnType()));
    ASTUtil.getModifiers(declaration).addAll(newModifiers(ast, binding.getModifiers()));
    Types.addBinding(declaration, binding);
    return declaration;
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

/**
 * @param n for positioning.// ww w  .ja v  a 2 s  .  co  m
 *
 * Make a constructor with parameters that calls super(...) with parameters. Used for anonymous classes with arguments to a
 * constructor, like new Foo(arg1,arg2) { }
 */
private CAstEntity createDefaultConstructorWithParameters(IMethodBinding ctor, ASTNode n,
        WalkContext oldContext, ArrayList<ASTNode> inits) {
    // PART I: find super ctor to call
    ITypeBinding newType = ctor.getDeclaringClass();
    ITypeBinding superType = newType.getSuperclass();
    IMethodBinding superCtor = null;

    for (IMethodBinding m : superType.getDeclaredMethods())
        if (m.isConstructor() && Arrays.equals(m.getParameterTypes(), ctor.getParameterTypes()))
            superCtor = m;

    assert superCtor != null : "couldn't find constructor for anonymous class";

    // PART II: make ctor with simply "super(a,b,c...)"
    final Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<CAstNode, CAstEntity>();
    final MethodContext context = new MethodContext(oldContext, memberEntities);
    MethodDeclaration fakeCtor = ast.newMethodDeclaration();
    fakeCtor.setConstructor(true);
    fakeCtor.setSourceRange(n.getStartPosition(), n.getLength());
    fakeCtor.setBody(ast.newBlock());

    // PART IIa: make a fake JDT constructor method with the proper number of args
    // Make fake args that will be passed
    String[] fakeArguments = new String[superCtor.getParameterTypes().length + 1];
    ArrayList<CAstType> paramTypes = new ArrayList<CAstType>(superCtor.getParameterTypes().length);
    for (int i = 0; i < fakeArguments.length; i++)
        fakeArguments[i] = (i == 0) ? "this" : ("argument" + i); // TODO: change to invalid name and don't use
                                                                 // singlevariabledeclaration below
    for (int i = 1; i < fakeArguments.length; i++) {
        // the name
        SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
        svd.setName(ast.newSimpleName(fakeArguments[i]));
        fakeCtor.parameters().add(svd);

        // the type
        paramTypes.add(fTypeDict.getCAstTypeFor(ctor.getParameterTypes()[i - 1]));
    }

    // PART IIb: create the statements in the constructor
    // one super() call plus the inits
    CAstNode[] bodyNodes = new CAstNode[inits.size() + 1];

    // make super(...) call
    // this, call ref, args
    CAstNode[] children = new CAstNode[fakeArguments.length + 1];
    children[0] = makeNode(context, fFactory, n, CAstNode.SUPER);
    CallSiteReference callSiteRef = CallSiteReference.make(0, fIdentityMapper.getMethodRef(superCtor),
            IInvokeInstruction.Dispatch.SPECIAL);
    children[1] = fFactory.makeConstant(callSiteRef);
    for (int i = 1; i < fakeArguments.length; i++) {
        CAstNode argName = fFactory.makeConstant(fakeArguments[i]);
        CAstNode argType = fFactory.makeConstant(paramTypes.get(i - 1));
        children[i + 1] = makeNode(context, fFactory, n, CAstNode.VAR, argName, argType);
    }
    bodyNodes[0] = makeNode(context, fFactory, n, CAstNode.CALL, children);
    // QUESTION: no handleExceptions?

    for (int i = 0; i < inits.size(); i++)
        bodyNodes[i + 1] = visitFieldInitNode(inits.get(i), context);

    // finally, make the procedure entity
    CAstNode ast = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, bodyNodes);
    return new ProcedureEntity(ast, fakeCtor, newType, memberEntities, context, paramTypes, null, null);

}