Example usage for org.eclipse.jdt.core.dom AST newArrayType

List of usage examples for org.eclipse.jdt.core.dom AST newArrayType

Introduction

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

Prototype

public ArrayType newArrayType(Type elementType) 

Source Link

Document

Creates and returns a new unparented array type node with the given element type, which cannot be an array type for API levels JLS8 and later.

Usage

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

License:Open Source License

private ExpressionStatement makeAssignmentStatement(VariableDeclarationFragment fragment) {
    AST ast = fragment.getAST();
    IVariableBinding varBinding = Types.getVariableBinding(fragment);
    Assignment assignment = ast.newAssignment();
    Types.addBinding(assignment, varBinding.getType());
    Expression lhs = ast.newSimpleName(fragment.getName().getIdentifier());
    Types.addBinding(lhs, varBinding);
    assignment.setLeftHandSide(lhs);/*from   w w w.  jav a  2 s. c  om*/

    Expression initializer = fragment.getInitializer();
    if (initializer instanceof ArrayInitializer) {
        // An array initializer cannot be directly assigned, since by itself
        // it's just shorthand for an array creation node.  This therefore
        // builds an array creation node with the existing initializer.
        ArrayCreation arrayCreation = ast.newArrayCreation();
        ITypeBinding arrayType = varBinding.getType();
        Types.addBinding(arrayCreation, arrayType);
        Type newType = Types.makeIOSType(arrayType);
        assert newType != null;
        ArrayType newArrayType = ast.newArrayType(newType);
        Types.addBinding(newArrayType, arrayType);
        arrayCreation.setType(newArrayType);
        arrayCreation.setInitializer((ArrayInitializer) NodeCopier.copySubtree(ast, initializer));
        assignment.setRightHandSide(arrayCreation);
    } else {
        assignment.setRightHandSide(NodeCopier.copySubtree(ast, initializer));
    }
    return ast.newExpressionStatement(assignment);
}

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

License:Apache License

public static Type newType(AST ast, ITypeBinding binding) {
    Type type;//from   w  ww.  j  a  va  2s  . co m
    if (binding.isPrimitive()) {
        type = ast.newPrimitiveType(PrimitiveType.toCode(binding.getName()));
    } else if (binding.isArray()) {
        type = ast.newArrayType(newType(ast, binding.getComponentType()));
    } else if (binding instanceof PointerTypeBinding) {
        type = newType(ast, ((PointerTypeBinding) binding).getPointeeType());
    } else {
        type = ast.newSimpleType(newSimpleName(ast, binding.getErasure()));
    }
    Types.addBinding(type, binding);
    return type;
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected Type getType(AST ast, String type) {
    Type returnType = null;//from   ww w. jav a 2 s .  c  o  m

    if (type != null) {
        boolean isArray = false;
        boolean isGenericType = false;
        if (type.indexOf("[") != -1) {
            isArray = true;
        }
        if (type.indexOf("<") != -1) {
            isGenericType = true;
        }

        try {
            if (isArray) {
                returnType = ast.newArrayType(
                        ast.newSimpleType(ast.newSimpleName(type.substring(0, type.indexOf("[")))));
            } else if (isGenericType) {
                returnType = ast.newParameterizedType(
                        ast.newSimpleType(ast.newSimpleName(type.substring(0, type.indexOf("<")))));

                StringTokenizer tokens = new StringTokenizer(
                        type.substring(type.indexOf("<") + 1, type.indexOf(">")), ",");
                while (tokens.hasMoreTokens()) {
                    ((ParameterizedType) returnType).typeArguments()
                            .add(getType(ast, tokens.nextToken().trim()));
                }
            } else {
                returnType = ast.newSimpleType(ast.newSimpleName(type));
            }
        } catch (IllegalArgumentException iae) {
            if (isArray) {
                returnType = ast.newArrayType(
                        ast.newPrimitiveType(PrimitiveType.toCode(type.substring(0, type.indexOf("[")))));
            } else {
                returnType = ast.newPrimitiveType(PrimitiveType.toCode(type));
            }
        }
    } else {
        returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    }

    return returnType;
}

From source file:de.crowdcode.kissmda.core.jdt.JdtHelper.java

License:Apache License

/**
 * Get JDT ArrayType for the given type name.
 * /*from   w  w w .j  a v a 2s . c  om*/
 * @param ast
 *            JDT AST tree
 * @param typeName
 *            input type name
 * @return JDT ArrayType
 */
public ArrayType getAstArrayType(AST ast, String typeName) {
    Type componentType = null;
    // Remove [] for componentType
    typeName = StringUtils.remove(typeName, "[]");
    if (dataTypeUtils.isPrimitiveType(typeName)) {
        componentType = getAstPrimitiveType(ast, typeName);
    } else {
        componentType = getAstSimpleType(ast, typeName);
    }

    ArrayType arrayType = ast.newArrayType(componentType);
    return arrayType;
}

From source file:org.autorefactor.refactoring.ASTHelper.java

License:Open Source License

/**
 * Converts the provided type binding to a new {@link Type} object.
 *
 * @param ast the {@link AST}/*from ww  w  .  j  a v  a 2s  .  com*/
 * @param typeBinding the type binding
 * @return a new {@link Type} object
 */
public static Type toType(final AST ast, final ITypeBinding typeBinding) {
    if (typeBinding == null) {
        return null;
    } else if (typeBinding.isArray()) {
        return ast.newArrayType(toType(ast, typeBinding.getComponentType()));
    } else if (typeBinding.isPrimitive()) {
        final Code primitiveTypeCode = PrimitiveType.toCode(typeBinding.getName());
        if (primitiveTypeCode != null) {
            return ast.newPrimitiveType(primitiveTypeCode);
        }
    } else if (typeBinding.isClass() || typeBinding.isInterface()) {
        final Type result = toType(ast, typeBinding.getQualifiedName());
        if (result == null) {
            throw new IllegalStateException(null,
                    "Cannot create a new type from an ITypeBinding without qualified name: " + typeBinding);
        }
        return result;
    }
    throw new NotImplementedException(null,
            "Unknown type for typeBinding " + typeBinding.getQualifiedName() + ", isAnnotation()="
                    + typeBinding.isAnnotation() + ", isAnonymous()=" + typeBinding.isAnonymous()
                    + ", isCapture()=" + typeBinding.isCapture() + ", isEnum()=" + typeBinding.isEnum()
                    + ", isGenericType()=" + typeBinding.isGenericType() + ", isParameterizedType()="
                    + typeBinding.isParameterizedType() + ", isTypeVariable()=" + typeBinding.isTypeVariable()
                    + ", isRawType()=" + typeBinding.isRawType() + ", isWildcardType()="
                    + typeBinding.isWildcardType());
}

From source file:org.decojer.cavaj.utils.Expressions.java

License:Open Source License

/**
 * New type.//ww  w  . jav a  2 s. c  om
 *
 * @param t
 *            type
 * @param context
 *            context
 * @return AST type
 */
@SuppressWarnings("deprecation")
public static Type newType(@Nonnull final T t, @Nonnull final Element context) {
    final AST ast = context.getCu().getAst();
    // handle array first because annot(array()) is special
    if (t.isArray()) {
        if (ast.apiLevel() <= AST.JLS4) {
            final T componentT = t.getComponentT();
            assert componentT != null;
            return ast.newArrayType(newType(componentT, context));
        }
        final T elementT = t.getElementT();
        assert elementT != null;
        for (T checkT = t; checkT != null && checkT.isArray(); checkT = checkT.getComponentT()) {
            if (checkT.isAnnotated()) {
                final ArrayType arrayType = ast.newArrayType(newType(elementT, context));
                final List<Dimension> dimensions = arrayType.dimensions();
                dimensions.clear();
                for (T componentT = t; componentT != null
                        && componentT.isArray(); componentT = componentT.getComponentT()) {
                    final Dimension dimension = ast.newDimension();
                    final List<IExtendedModifier> annotations = dimension.annotations();
                    assert annotations != null;
                    if (componentT.isAnnotated()) {
                        Annotations.decompileAnnotations(componentT, annotations, context);
                    }
                    dimensions.add(dimension);
                }
                return arrayType;
            }
        }
        return ast.newArrayType(newType(elementT, context), t.getDimensions());
    }
    if (t.isAnnotated()) {
        Type type = newType(t.getRawT(), context);
        if (ast.apiLevel() <= AST.JLS4) {
            log.warn("Cannot decompile type annotations for type '" + t + "' in Eclipse AST JLS4!");
            return type;
        }
        // parameterized type is not directly annotateable in Eclipse; but DecoJer thinks the
        // whole type is meant, not just the generic type, hence translate here
        AnnotatableType annotatableType = (AnnotatableType) (type instanceof ParameterizedType
                ? ((ParameterizedType) type).getType()
                : type);
        qualified: if (annotatableType instanceof SimpleType) {
            // direct annotation of qualified types adds the annotations as first element,
            // strange Java spec doesn't allow "@A package.Name" but wants "package.@A Name"
            final Name typeName = ((SimpleType) annotatableType).getName();
            if (!(typeName instanceof QualifiedName)) {
                break qualified;
            }
            final Name qualifier = ((QualifiedName) typeName).getQualifier();
            final SimpleName name = ((QualifiedName) typeName).getName();
            // cannot delete mandory childs, copy them
            annotatableType = ast.newNameQualifiedType((Name) ASTNode.copySubtree(ast, qualifier),
                    (SimpleName) ASTNode.copySubtree(ast, name));
            if (type instanceof ParameterizedType) {
                ((ParameterizedType) type).setType(annotatableType);
            } else {
                type = annotatableType;
            }
        }
        final List<IExtendedModifier> annotations = annotatableType.annotations();
        assert annotations != null;
        Annotations.decompileAnnotations(t, annotations, context);
        return type;
    }
    // doesn't work, now with Dimension (see above): if (t.isArray()) { return
    // ast.newArrayType(newType(t.getComponentT(), contextT)); }
    if (t.isParameterized()) {
        final T genericT = t.getGenericT();
        assert genericT != null;
        final ParameterizedType parameterizedType = ast.newParameterizedType(newType(genericT, context));
        for (final T typeArg : t.getTypeArgs()) {
            assert typeArg != null;
            parameterizedType.typeArguments().add(newType(typeArg, context));
        }
        return parameterizedType;
    }
    if (t.isWildcard()) {
        final T boundT = t.getBoundT();
        if (boundT == null) {
            return ast.newWildcardType();
        }
        if (t.isSubclassOf()) {
            final WildcardType wildcardType = ast.newWildcardType();
            // default...newWildcardType.setUpperBound(true);
            wildcardType.setBound(newType(boundT, context));
            return wildcardType;
        }
        final WildcardType wildcardType = ast.newWildcardType();
        wildcardType.setUpperBound(false);
        wildcardType.setBound(newType(boundT, context));
        return wildcardType;
    }
    if (t.isMulti()) {
        log.warn("Convert type for multi-type '" + t + "'!");
        // prefer boolean for multi-type with 0 or 1, synchronous to newLiteral()!
        // prefer byte before char if no explicit char type given
    }
    if (t.is(T.BOOLEAN)) {
        return ast.newPrimitiveType(PrimitiveType.BOOLEAN);
    }
    if (t.is(T.BYTE)) {
        return ast.newPrimitiveType(PrimitiveType.BYTE);
    }
    if (t.is(T.CHAR)) {
        return ast.newPrimitiveType(PrimitiveType.CHAR);
    }
    if (t.is(T.SHORT)) {
        return ast.newPrimitiveType(PrimitiveType.SHORT);
    }
    if (t.is(T.INT)) {
        return ast.newPrimitiveType(PrimitiveType.INT);
    }
    if (t.is(T.FLOAT)) {
        return ast.newPrimitiveType(PrimitiveType.FLOAT);
    }
    if (t.is(T.LONG)) {
        return ast.newPrimitiveType(PrimitiveType.LONG);
    }
    if (t.is(T.DOUBLE)) {
        return ast.newPrimitiveType(PrimitiveType.DOUBLE);
    }
    if (t.is(T.VOID)) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    if (t.isQualified()) {
        final T qualifierT = t.getQualifierT();
        assert qualifierT != null : "cannot be null for qualified";
        // could be ParamT etc., not decompileable with name as target;
        // restrict qualifications to really necessary enclosings:
        // t = Outer.Inner.InnerInner, t = Outer.Inner ==> Inner
        final T contextT = context.getT();
        assert contextT != null;
        if (contextT.getFullName().startsWith(qualifierT.getFullName())) {
            // TODO full name has too much info yet (like annotations)
            return ast.newSimpleType(newSimpleName(t.getSimpleIdentifier(), ast));
        }
        return ast.newQualifiedType(newType(qualifierT, context), newSimpleName(t.getSimpleIdentifier(), ast));
    }
    // else fall through...
    return ast.newSimpleType(newTypeName(t, context));
}

From source file:org.eclipse.pde.api.tools.internal.util.Signatures.java

License:Open Source License

private static Type getType(ASTNode node) {
    switch (node.getNodeType()) {
    case ASTNode.SINGLE_VARIABLE_DECLARATION: {
        SingleVariableDeclaration param = (SingleVariableDeclaration) node;
        Type type = param.getType();
        int extraDim = param.getExtraDimensions();

        if (extraDim == 0) {
            return type;
        }/*from   w  ww. j  av a  2 s .  c o m*/
        AST ast = type.getAST();
        type = (Type) ASTNode.copySubtree(ast, type);
        for (int i = 0; i < extraDim; i++) {
            type = ast.newArrayType(type);
        }
        return type;
    }
    default: {
        // ASTNode.METHOD_DECLARATION
        MethodDeclaration methodDeclaration = (MethodDeclaration) node;
        Type type = methodDeclaration.getReturnType2();
        int extraDim = methodDeclaration.getExtraDimensions();

        if (extraDim == 0) {
            return type;
        }
        AST ast = type.getAST();
        type = (Type) ASTNode.copySubtree(ast, type);
        for (int i = 0; i < extraDim; i++) {
            type = ast.newArrayType(type);
        }
        return type;
    }
    }
}

From source file:org.evosuite.testcarver.codegen.CodeGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private MethodInvocation createCallMethodOrNewInstanceCallStmt(final boolean isConstructorCall, final AST ast,
        final String varName, final String targetTypeName, final String methodName, final Object[] methodArgs,
        final org.objectweb.asm.Type[] paramTypes) {
    //-- construct getField() call
    final MethodInvocation callMethodCall = ast.newMethodInvocation();

    if (isConstructorCall) {
        callMethodCall.setName(ast.newSimpleName("newInstance"));
    } else {//from   w ww. ja  v a2 s. c o m
        callMethodCall.setName(ast.newSimpleName("callMethod"));
    }

    StringLiteral stringLiteral = ast.newStringLiteral();
    stringLiteral.setLiteralValue(targetTypeName);
    callMethodCall.arguments().add(stringLiteral); // class name

    if (!isConstructorCall) {
        stringLiteral = ast.newStringLiteral();
        stringLiteral.setLiteralValue(methodName);
        callMethodCall.arguments().add(stringLiteral); // method name

        if (varName == null) {
            callMethodCall.arguments().add(ast.newNullLiteral()); // static call -> no receiver
        } else {
            callMethodCall.arguments().add(ast.newSimpleName(varName)); // receiver
        }
    }

    // method arguments
    ArrayCreation arrCreation = ast.newArrayCreation();
    arrCreation.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Object"))));
    ArrayInitializer arrInit = ast.newArrayInitializer();
    arrCreation.setInitializer(arrInit);
    callMethodCall.arguments().add(arrCreation);

    Integer arg; // is either an oid or null
    for (int i = 0; i < methodArgs.length; i++) {
        arg = (Integer) methodArgs[i];
        if (arg == null) {
            arrInit.expressions().add(ast.newNullLiteral());
        } else {
            arrInit.expressions().add(ast.newSimpleName(this.oidToVarMapping.get(arg)));
        }
    }

    // paramTypes
    arrCreation = ast.newArrayCreation();
    arrCreation.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Class"))));
    arrInit = ast.newArrayInitializer();
    arrCreation.setInitializer(arrInit);
    callMethodCall.arguments().add(arrCreation);

    org.objectweb.asm.Type type;
    for (int i = 0; i < paramTypes.length; i++) {
        type = paramTypes[i];

        if (type.equals(org.objectweb.asm.Type.BOOLEAN_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Boolean"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.BYTE_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Byte"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.CHAR_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Character"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.DOUBLE_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Double"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.FLOAT_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Float"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.INT_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Integer"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.LONG_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Long"));
            arrInit.expressions().add(facc);
        } else if (type.equals(org.objectweb.asm.Type.SHORT_TYPE)) {
            FieldAccess facc = ast.newFieldAccess();
            facc.setName(ast.newSimpleName("TYPE"));
            facc.setExpression(ast.newSimpleName("Short"));
            arrInit.expressions().add(facc);
        } else {
            final TypeLiteral clazz = ast.newTypeLiteral();
            clazz.setType(ast.newSimpleType(ast.newName(type.getClassName())));

            arrInit.expressions().add(clazz);
        }
    }

    return callMethodCall;
}

From source file:org.evosuite.testcarver.codegen.CodeGenerator.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
private void createCallMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) {
    //      public static Object callMethod(final String clazzName, final String methodName, final Object receiver, final Object...args) throws Exception
    //      {//from w  w  w  .  j a va2s.c  o m
    //         final Class<?> clazz = Class.forName(clazzName);
    //         final Method   m     = clazz.getDeclaredMethod(methodName);
    //         m.setAccessible(true);
    //         return m.invoke(receiver, args);
    //      }

    //-- add necessary import statements
    List imports = cu.imports();
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Method" }));
    imports.add(id);

    //-- create method frame: "public static Object callMethod(final String clazzName, final String methodName, final Object receiver, final Object[] args, Class[] paramTypes) throws Exception"
    final MethodDeclaration md = ast.newMethodDeclaration();
    td.bodyDeclarations().add(md);
    md.setName(ast.newSimpleName("callMethod"));

    List modifiers = md.modifiers();
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));

    md.thrownExceptions().add(ast.newSimpleName("Exception"));

    List parameters = md.parameters();

    SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("String")));
    svd.setName(ast.newSimpleName("clazzName"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("String")));
    svd.setName(ast.newSimpleName("methodName"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("Object")));
    svd.setName(ast.newSimpleName("receiver"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Object"))));
    svd.setName(ast.newSimpleName("args"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Class"))));
    svd.setName(ast.newSimpleName("paramTypes"));
    parameters.add(svd);

    md.setReturnType2(ast.newSimpleType(ast.newSimpleName("Object")));

    //-- create method body
    //      final Class<?> clazz = Class.forName(clazzName);
    //      final Method   m     = clazz.getDeclaredMethod(methodName, paramTypes);
    //      m.setAccessible(true);
    //      return m.invoke(receiver, args);

    final Block methodBlock = ast.newBlock();
    md.setBody(methodBlock);
    final List methodStmts = methodBlock.statements();

    // final Class clazz = Class.forName(clazzName);      
    MethodInvocation init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("forName"));
    init.setExpression(ast.newSimpleName("Class"));
    init.arguments().add(ast.newSimpleName("clazzName"));
    VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("clazz"));
    varDeclFrag.setInitializer(init);
    VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Class")));
    methodStmts.add(varDeclStmt);

    // final Method m = clazz.getDeclaredMethod(methodName);
    init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("getDeclaredMethod"));
    init.setExpression(ast.newSimpleName("clazz"));
    init.arguments().add(ast.newSimpleName("methodName"));
    init.arguments().add(ast.newSimpleName("paramTypes"));
    varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("m"));
    varDeclFrag.setInitializer(init);
    varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Method")));
    methodStmts.add(varDeclStmt);

    // f.setAccessible(true);
    MethodInvocation minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("setAccessible"));
    minv.setExpression(ast.newSimpleName("m"));
    minv.arguments().add(ast.newBooleanLiteral(true));
    methodStmts.add(ast.newExpressionStatement(minv));

    // return m.invoke(receiver, args);
    minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("invoke"));
    minv.setExpression(ast.newSimpleName("m"));
    minv.arguments().add(ast.newSimpleName("receiver"));
    minv.arguments().add(ast.newSimpleName("args"));
    final ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(minv);
    methodStmts.add(returnStmt);
}

From source file:org.evosuite.testcarver.codegen.CodeGenerator.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
private void createNewInstanceMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) {
    //      public static Object newInstance(final String clazzName, final Object receiver, final Object[] args, final Class[] parameterTypes) throws Exception
    //      {/*from www  .j a  v a2  s. c o  m*/
    //         final Class<?>     clazz = Class.forName(clazzName);
    //         final Constructor   c    = clazz.getDeclaredConstructor(parameterTypes);
    //         c.setAccessible(true);
    //         
    //         return c.newInstance(args);
    //      }

    //-- add necessary import statements
    List imports = cu.imports();
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Constructor" }));
    imports.add(id);

    //-- create method frame: "public static Object newInstance(final String clazzName, final Object[] args, Class[] paramTypes) throws Exception"
    final MethodDeclaration md = ast.newMethodDeclaration();
    td.bodyDeclarations().add(md);
    md.setName(ast.newSimpleName("newInstance"));

    List modifiers = md.modifiers();
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
    modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));

    md.thrownExceptions().add(ast.newSimpleName("Exception"));

    List parameters = md.parameters();

    SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newSimpleType(ast.newSimpleName("String")));
    svd.setName(ast.newSimpleName("clazzName"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Object"))));
    svd.setName(ast.newSimpleName("args"));
    parameters.add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Class"))));
    svd.setName(ast.newSimpleName("paramTypes"));
    parameters.add(svd);

    md.setReturnType2(ast.newSimpleType(ast.newSimpleName("Object")));

    //-- create method body
    //      final Class<?>     clazz = Class.forName(clazzName);
    //      final Constructor   c    = clazz.getDeclaredConstructor(parameterTypes);
    //      c.setAccessible(true);
    //      
    //      return c.newInstance(args);

    final Block methodBlock = ast.newBlock();
    md.setBody(methodBlock);
    final List methodStmts = methodBlock.statements();

    // final Class clazz = Class.forName(clazzName);      
    MethodInvocation init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("forName"));
    init.setExpression(ast.newSimpleName("Class"));
    init.arguments().add(ast.newSimpleName("clazzName"));
    VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("clazz"));
    varDeclFrag.setInitializer(init);
    VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Class")));
    methodStmts.add(varDeclStmt);

    // final Constructor c = clazz.getDeclaredConstructor(parameterTypes);
    init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("getDeclaredConstructor"));
    init.setExpression(ast.newSimpleName("clazz"));
    init.arguments().add(ast.newSimpleName("paramTypes"));
    varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("c"));
    varDeclFrag.setInitializer(init);
    varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Constructor")));
    methodStmts.add(varDeclStmt);

    // c.setAccessible(true);
    MethodInvocation minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("setAccessible"));
    minv.setExpression(ast.newSimpleName("c"));
    minv.arguments().add(ast.newBooleanLiteral(true));
    methodStmts.add(ast.newExpressionStatement(minv));

    // return c.newInstance(args);
    minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("newInstance"));
    minv.setExpression(ast.newSimpleName("c"));
    minv.arguments().add(ast.newSimpleName("args"));
    final ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(minv);
    methodStmts.add(returnStmt);
}