Search in sources :

Example 1 with FieldDeclaration

use of com.github.antlrjavaparser.api.body.FieldDeclaration in project spring-roo by spring-projects.

the class JavaParserFieldMetadataBuilder method addField.

public static void addField(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final FieldMetadata field) {
    Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
    Validate.notNull(members, "Members required");
    Validate.notNull(field, "Field required");
    JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), field.getFieldType());
    final Type initType = JavaParserUtils.getResolvedName(compilationUnitServices.getEnclosingTypeName(), field.getFieldType(), compilationUnitServices);
    final ClassOrInterfaceType finalType = JavaParserUtils.getClassOrInterfaceType(initType);
    final FieldDeclaration newField = ASTHelper.createFieldDeclaration(JavaParserUtils.getJavaParserModifier(field.getModifier()), initType, field.getFieldName().getSymbolName());
    // Add parameterized types for the field type (not initializer)
    if (field.getFieldType().getParameters().size() > 0) {
        final List<Type> fieldTypeArgs = new ArrayList<Type>();
        finalType.setTypeArgs(fieldTypeArgs);
        for (final JavaType parameter : field.getFieldType().getParameters()) {
            fieldTypeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
        }
    }
    final List<VariableDeclarator> vars = newField.getVariables();
    Validate.notEmpty(vars, "Expected ASTHelper to have provided a single VariableDeclarator");
    Validate.isTrue(vars.size() == 1, "Expected ASTHelper to have provided a single VariableDeclarator");
    final VariableDeclarator vd = vars.iterator().next();
    if (StringUtils.isNotBlank(field.getFieldInitializer())) {
        // There is an initializer.
        // We need to make a fake field that we can have JavaParser parse.
        // Easiest way to do that is to build a simple source class
        // containing the required field and re-parse it.
        final StringBuilder sb = new StringBuilder();
        sb.append("class TemporaryClass {\n");
        sb.append("  private " + field.getFieldType() + " " + field.getFieldName() + " = " + field.getFieldInitializer() + ";\n");
        sb.append("}\n");
        final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
        CompilationUnit ci;
        try {
            ci = JavaParser.parse(bais);
        } catch (final IOException e) {
            throw new IllegalStateException("Illegal state: Unable to parse input stream", e);
        } catch (final ParseException pe) {
            throw new IllegalStateException("Illegal state: JavaParser did not parse correctly", pe);
        }
        final List<TypeDeclaration> types = ci.getTypes();
        if (types == null || types.size() != 1) {
            throw new IllegalArgumentException("Field member invalid");
        }
        final TypeDeclaration td = types.get(0);
        final List<BodyDeclaration> bodyDeclarations = td.getMembers();
        if (bodyDeclarations == null || bodyDeclarations.size() != 1) {
            throw new IllegalStateException("Illegal state: JavaParser did not return body declarations correctly");
        }
        final BodyDeclaration bd = bodyDeclarations.get(0);
        if (!(bd instanceof FieldDeclaration)) {
            throw new IllegalStateException("Illegal state: JavaParser did not return a field declaration correctly");
        }
        final FieldDeclaration fd = (FieldDeclaration) bd;
        if (fd.getVariables() == null || fd.getVariables().size() != 1) {
            throw new IllegalStateException("Illegal state: JavaParser did not return a field declaration correctly");
        }
        final Expression init = fd.getVariables().get(0).getInit();
        // Resolve imports (ROO-1505)
        if (init instanceof ObjectCreationExpr) {
            final ObjectCreationExpr ocr = (ObjectCreationExpr) init;
            final JavaType typeToImport = JavaParserUtils.getJavaTypeNow(compilationUnitServices, ocr.getType(), null);
            final NameExpr nameExpr = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), typeToImport);
            final ClassOrInterfaceType classOrInterfaceType = JavaParserUtils.getClassOrInterfaceType(nameExpr);
            ocr.setType(classOrInterfaceType);
            if (typeToImport.getParameters().size() > 0) {
                final List<Type> initTypeArgs = new ArrayList<Type>();
                finalType.setTypeArgs(initTypeArgs);
                for (final JavaType parameter : typeToImport.getParameters()) {
                    initTypeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
                }
                classOrInterfaceType.setTypeArgs(initTypeArgs);
            }
        }
        vd.setInit(init);
    }
    // Add annotations
    final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
    newField.setAnnotations(annotations);
    for (final AnnotationMetadata annotation : field.getAnnotations()) {
        JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
    }
    // ROO-3678: Add-on which include new field should be the responsible to check if field
    // exists, not JavaParser.
    /*// Locate where to add this field; also verify if this field already
    // exists
    int nextFieldIndex = 0;
    int i = -1;
    for (final BodyDeclaration bd : members) {
        i++;
        if (bd instanceof FieldDeclaration) {
            // Next field should appear after this current field
            nextFieldIndex = i + 1;
            final FieldDeclaration bdf = (FieldDeclaration) bd;
            for (final VariableDeclarator v : bdf.getVariables()) {
                Validate.isTrue(!field.getFieldName().getSymbolName()
                        .equals(v.getId().getName()),
                        "A field with name '%s' already exists", field
                                .getFieldName().getSymbolName());
            }
        }
    }*/
    int nextFieldIndex = 0;
    int i = -1;
    for (final BodyDeclaration bd : members) {
        i++;
        if (bd instanceof FieldDeclaration) {
            // Next field should appear after this current field
            nextFieldIndex = i + 1;
        }
    }
    if (field.getCommentStructure() != null) {
        // annotation
        if (annotations != null && annotations.size() > 0) {
            AnnotationExpr firstAnnotation = annotations.get(0);
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, field.getCommentStructure());
        // Otherwise, add comments to the field declaration line
        } else {
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(newField, field.getCommentStructure());
        }
    } else {
        // ROO-3834: Append default Javadoc if not exists a comment structure
        CommentStructure defaultCommentStructure = new CommentStructure();
        JavadocComment javadocComment = new JavadocComment("TODO Auto-generated attribute documentation");
        defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
        field.setCommentStructure(defaultCommentStructure);
        // annotation
        if (annotations != null && annotations.size() > 0) {
            AnnotationExpr firstAnnotation = annotations.get(0);
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
        // Otherwise, add comments to the field declaration line
        } else {
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(newField, defaultCommentStructure);
        }
    }
    // Add the field to the compilation unit
    members.add(nextFieldIndex, newField);
}
Also used : ObjectCreationExpr(com.github.antlrjavaparser.api.expr.ObjectCreationExpr) AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) ArrayList(java.util.ArrayList) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) FieldDeclaration(com.github.antlrjavaparser.api.body.FieldDeclaration) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) VariableDeclarator(com.github.antlrjavaparser.api.body.VariableDeclarator) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) IOException(java.io.IOException) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) JavaType(org.springframework.roo.model.JavaType) Type(com.github.antlrjavaparser.api.type.Type) JavaType(org.springframework.roo.model.JavaType) ByteArrayInputStream(java.io.ByteArrayInputStream) Expression(com.github.antlrjavaparser.api.expr.Expression) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) ParseException(com.github.antlrjavaparser.ParseException) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration)

Example 2 with FieldDeclaration

use of com.github.antlrjavaparser.api.body.FieldDeclaration in project spring-roo by spring-projects.

the class UpdateCompilationUnitUtils method updateFields.

/**
 * Update {@code originalType} fields from {@code newType} information
 *
 * @param originalType
 * @param newType
 */
private static void updateFields(final TypeDeclaration originalType, final TypeDeclaration newType) {
    // Get a map of all fields (as FieldDeclaration could contain more than
    // one field)
    final Map<String, FieldEntry> cidFields = new HashMap<String, FieldEntry>();
    String fieldName;
    FieldDeclaration field;
    if (newType.getMembers() != null) {
        for (final BodyDeclaration element : newType.getMembers()) {
            if (element instanceof FieldDeclaration) {
                field = (FieldDeclaration) element;
                for (final VariableDeclarator variable : field.getVariables()) {
                    fieldName = variable.getId().getName();
                    cidFields.put(fieldName, new FieldEntry(field, variable));
                }
            }
        }
    }
    // Iterate over every field definition
    if (originalType.getMembers() != null) {
        for (final Iterator<BodyDeclaration> originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext(); ) {
            final BodyDeclaration originalMember = originalMemberstIter.next();
            if (!(originalMember instanceof FieldDeclaration)) {
                // this is not a field definition
                continue;
            }
            field = (FieldDeclaration) originalMember;
            // Check every variable declared in definition
            for (final Iterator<VariableDeclarator> variablesIter = field.getVariables().iterator(); variablesIter.hasNext(); ) {
                final VariableDeclarator originalVariable = variablesIter.next();
                fieldName = originalVariable.getId().getName();
                // look for field name in cid
                final FieldEntry entry = cidFields.get(fieldName);
                if (entry == null) {
                    // Not found: remove field from original compilation
                    // unit
                    variablesIter.remove();
                    continue;
                }
                // Check modifiers, type and annotations
                if (equalFieldTypeModifiersAnnotations(field, entry.fieldDeclaration)) {
                    // Variable declaration is equals:
                    // remove from cid map as already exists
                    cidFields.remove(fieldName);
                } else {
                    // as there are more variable definition remove it
                    // from original. At the end, process will create it
                    // again
                    // using new modifiers and type
                    variablesIter.remove();
                    // Modifiers changed
                    if (field.getVariables().size() == 1) {
                        // if no more variables update all field definition
                        field.setModifiers(entry.fieldDeclaration.getModifiers());
                        field.setType(entry.fieldDeclaration.getType());
                        if (field.getAnnotations() == null && entry.fieldDeclaration.getAnnotations() != null) {
                            field.setAnnotations(new ArrayList<AnnotationExpr>());
                        }
                        updateAnnotations(field.getAnnotations(), entry.fieldDeclaration.getAnnotations());
                        // remove processed field of cid
                        cidFields.remove(fieldName);
                        continue;
                    }
                }
            }
            if (field.getVariables().isEmpty()) {
                originalMemberstIter.remove();
            }
        }
    }
    if (cidFields.isEmpty()) {
        // Done it
        return;
    }
    if (originalType.getMembers() == null) {
        originalType.setMembers(new ArrayList<BodyDeclaration>());
    }
    // Add new fields
    List<VariableDeclarator> variables;
    for (final FieldEntry entry : cidFields.values()) {
        variables = new ArrayList<VariableDeclarator>(1);
        variables.add(entry.variableDeclarator);
        field = new FieldDeclaration(entry.fieldDeclaration.getModifiers(), entry.fieldDeclaration.getType(), variables);
        field.setAnnotations(entry.fieldDeclaration.getAnnotations());
        field.setBeginComments(entry.fieldDeclaration.getBeginComments());
        field.setInternalComments(entry.fieldDeclaration.getInternalComments());
        field.setEndComments(entry.fieldDeclaration.getEndComments());
        originalType.getMembers().add(field);
    }
}
Also used : AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) MarkerAnnotationExpr(com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr) SingleMemberAnnotationExpr(com.github.antlrjavaparser.api.expr.SingleMemberAnnotationExpr) NormalAnnotationExpr(com.github.antlrjavaparser.api.expr.NormalAnnotationExpr) HashMap(java.util.HashMap) FieldDeclaration(com.github.antlrjavaparser.api.body.FieldDeclaration) VariableDeclarator(com.github.antlrjavaparser.api.body.VariableDeclarator) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration)

Example 3 with FieldDeclaration

use of com.github.antlrjavaparser.api.body.FieldDeclaration in project spring-roo by spring-projects.

the class JavaParserClassOrInterfaceTypeDetailsBuilder method build.

@Override
public ClassOrInterfaceTypeDetails build() {
    Validate.notEmpty(compilationUnit.getTypes(), "No types in compilation unit, so unable to continue parsing");
    ClassOrInterfaceDeclaration clazz = null;
    EnumDeclaration enumClazz = null;
    final StringBuilder sb = new StringBuilder(compilationUnit.getPackage().getName().toString());
    if (name.getEnclosingType() != null) {
        sb.append(".").append(name.getEnclosingType().getSimpleTypeName());
    }
    compilationUnitPackage = new JavaPackage(sb.toString());
    // Determine the type name, adding type parameters if possible
    final JavaType newName = JavaParserUtils.getJavaType(compilationUnitServices, typeDeclaration);
    // Revert back to the original type name (thus avoiding unnecessary
    // inferences about java.lang types; see ROO-244)
    name = new JavaType(newName.getFullyQualifiedTypeName(), newName.getEnclosingType(), newName.getArray(), newName.getDataType(), newName.getArgName(), newName.getParameters(), name.getModule());
    final ClassOrInterfaceTypeDetailsBuilder cidBuilder = new ClassOrInterfaceTypeDetailsBuilder(declaredByMetadataId);
    physicalTypeCategory = PhysicalTypeCategory.CLASS;
    if (typeDeclaration instanceof ClassOrInterfaceDeclaration) {
        clazz = (ClassOrInterfaceDeclaration) typeDeclaration;
        if (clazz.isInterface()) {
            physicalTypeCategory = PhysicalTypeCategory.INTERFACE;
        }
    } else if (typeDeclaration instanceof EnumDeclaration) {
        enumClazz = (EnumDeclaration) typeDeclaration;
        physicalTypeCategory = PhysicalTypeCategory.ENUMERATION;
    }
    Validate.notNull(physicalTypeCategory, "%s (%s for %s)", UNSUPPORTED_MESSAGE_PREFIX, typeDeclaration.getClass().getSimpleName(), name);
    cidBuilder.setName(name);
    cidBuilder.setPhysicalTypeCategory(physicalTypeCategory);
    imports = compilationUnit.getImports();
    if (imports == null) {
        imports = new ArrayList<ImportDeclaration>();
        compilationUnit.setImports(imports);
    }
    // Verify the package declaration appears to be correct
    if (compilationUnitPackage.equals(name.getPackage()) != true) {
        String warningStr = "[Warning] Compilation unit package '" + compilationUnitPackage + "' unexpected for type '" + name.getPackage() + "', it may be a nested class.";
        LOGGER.log(Level.WARNING, warningStr);
    }
    for (final ImportDeclaration importDeclaration : imports) {
        if (importDeclaration.getName() instanceof QualifiedNameExpr) {
            final String qualifier = ((QualifiedNameExpr) importDeclaration.getName()).getQualifier().toString();
            final String simpleName = importDeclaration.getName().getName();
            final String fullName = qualifier + "." + simpleName;
            // We want to calculate these...
            final JavaType type = new JavaType(fullName);
            final JavaPackage typePackage = importDeclaration.isAsterisk() ? new JavaPackage(fullName) : type.getPackage();
            // Process any comments for the import
            final CommentStructure commentStructure = new CommentStructure();
            JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, importDeclaration);
            final ImportMetadataBuilder newImport = new ImportMetadataBuilder(declaredByMetadataId, 0, typePackage, type, importDeclaration.isStatic(), importDeclaration.isAsterisk());
            newImport.setCommentStructure(commentStructure);
            cidBuilder.add(newImport.build());
        }
    }
    // Convert Java Parser modifier into JDK modifier
    cidBuilder.setModifier(JavaParserUtils.getJdkModifier(typeDeclaration.getModifiers()));
    // Type parameters
    final Set<JavaSymbolName> typeParameterNames = new HashSet<JavaSymbolName>();
    for (final JavaType param : name.getParameters()) {
        final JavaSymbolName arg = param.getArgName();
        // Fortunately type names can only appear at the top-level
        if (arg != null && !JavaType.WILDCARD_NEITHER_ARG.equals(arg) && !JavaType.WILDCARD_EXTENDS_ARG.equals(arg) && !JavaType.WILDCARD_SUPER_ARG.equals(arg)) {
            typeParameterNames.add(arg);
        }
    }
    List<ClassOrInterfaceType> implementsList;
    List<AnnotationExpr> annotationsList = null;
    List<BodyDeclaration> members = null;
    if (clazz != null) {
        final List<ClassOrInterfaceType> extendsList = clazz.getExtends();
        if (extendsList != null) {
            for (final ClassOrInterfaceType candidate : extendsList) {
                final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
                cidBuilder.addExtendsTypes(javaType);
            }
        }
        final List<JavaType> extendsTypes = cidBuilder.getExtendsTypes();
        // Obtain the superclass, if this is a class and one is available
        if (physicalTypeCategory == PhysicalTypeCategory.CLASS && extendsTypes.size() == 1) {
            final JavaType superclass = extendsTypes.get(0);
            final String superclassId = typeLocationService.getPhysicalTypeIdentifier(superclass);
            PhysicalTypeMetadata superPtm = null;
            if (superclassId != null) {
                superPtm = (PhysicalTypeMetadata) metadataService.get(superclassId);
            }
            if (superPtm != null && superPtm.getMemberHoldingTypeDetails() != null) {
                cidBuilder.setSuperclass(superPtm.getMemberHoldingTypeDetails());
            }
        }
        implementsList = clazz.getImplements();
        if (implementsList != null) {
            for (final ClassOrInterfaceType candidate : implementsList) {
                final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
                cidBuilder.addImplementsType(javaType);
            }
        }
        annotationsList = typeDeclaration.getAnnotations();
        members = clazz.getMembers();
    }
    if (enumClazz != null) {
        final List<EnumConstantDeclaration> constants = enumClazz.getEntries();
        if (constants != null) {
            for (final EnumConstantDeclaration enumConstants : constants) {
                cidBuilder.addEnumConstant(new JavaSymbolName(enumConstants.getName()));
            }
        }
        implementsList = enumClazz.getImplements();
        annotationsList = enumClazz.getAnnotations();
        members = enumClazz.getMembers();
    }
    if (annotationsList != null) {
        for (final AnnotationExpr candidate : annotationsList) {
            final AnnotationMetadata md = JavaParserAnnotationMetadataBuilder.getInstance(candidate, compilationUnitServices).build();
            final CommentStructure commentStructure = new CommentStructure();
            JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, candidate);
            md.setCommentStructure(commentStructure);
            cidBuilder.addAnnotation(md);
        }
    }
    if (members != null) {
        // type in the signature of the enclosing type
        for (final BodyDeclaration bodyDeclaration : members) {
            if (bodyDeclaration instanceof TypeDeclaration) {
                // Found a type
                innerTypes.add((TypeDeclaration) bodyDeclaration);
            }
        }
        for (final BodyDeclaration member : members) {
            if (member instanceof FieldDeclaration) {
                final FieldDeclaration castMember = (FieldDeclaration) member;
                for (final VariableDeclarator var : castMember.getVariables()) {
                    final FieldMetadata field = JavaParserFieldMetadataBuilder.getInstance(declaredByMetadataId, castMember, var, compilationUnitServices, typeParameterNames).build();
                    final CommentStructure commentStructure = new CommentStructure();
                    JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
                    field.setCommentStructure(commentStructure);
                    cidBuilder.addField(field);
                }
            }
            if (member instanceof MethodDeclaration) {
                final MethodDeclaration castMember = (MethodDeclaration) member;
                final MethodMetadata method = JavaParserMethodMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
                final CommentStructure commentStructure = new CommentStructure();
                JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
                method.setCommentStructure(commentStructure);
                cidBuilder.addMethod(method);
            }
            if (member instanceof ConstructorDeclaration) {
                final ConstructorDeclaration castMember = (ConstructorDeclaration) member;
                final ConstructorMetadata constructor = JavaParserConstructorMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
                final CommentStructure commentStructure = new CommentStructure();
                JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
                constructor.setCommentStructure(commentStructure);
                cidBuilder.addConstructor(constructor);
            }
            if (member instanceof TypeDeclaration) {
                final TypeDeclaration castMember = (TypeDeclaration) member;
                final JavaType innerType = new JavaType(castMember.getName(), name);
                final String innerTypeMetadataId = PhysicalTypeIdentifier.createIdentifier(innerType, PhysicalTypeIdentifier.getPath(declaredByMetadataId));
                final ClassOrInterfaceTypeDetails cid = new JavaParserClassOrInterfaceTypeDetailsBuilder(compilationUnit, compilationUnitServices, castMember, innerTypeMetadataId, innerType, metadataService, typeLocationService).build();
                cidBuilder.addInnerType(cid);
            }
        }
    }
    return cidBuilder.build();
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) ClassOrInterfaceDeclaration(com.github.antlrjavaparser.api.body.ClassOrInterfaceDeclaration) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) JavaPackage(org.springframework.roo.model.JavaPackage) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) FieldDeclaration(com.github.antlrjavaparser.api.body.FieldDeclaration) VariableDeclarator(com.github.antlrjavaparser.api.body.VariableDeclarator) EnumConstantDeclaration(com.github.antlrjavaparser.api.body.EnumConstantDeclaration) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) ConstructorDeclaration(com.github.antlrjavaparser.api.body.ConstructorDeclaration) ClassOrInterfaceTypeDetailsBuilder(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder) ImportMetadataBuilder(org.springframework.roo.classpath.details.ImportMetadataBuilder) HashSet(java.util.HashSet) MethodDeclaration(com.github.antlrjavaparser.api.body.MethodDeclaration) EnumDeclaration(com.github.antlrjavaparser.api.body.EnumDeclaration) JavaType(org.springframework.roo.model.JavaType) ConstructorMetadata(org.springframework.roo.classpath.details.ConstructorMetadata) PhysicalTypeMetadata(org.springframework.roo.classpath.PhysicalTypeMetadata) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration)

Example 4 with FieldDeclaration

use of com.github.antlrjavaparser.api.body.FieldDeclaration in project spring-roo by spring-projects.

the class JavaParserFieldMetadataBuilder method removeField.

public static void removeField(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final JavaSymbolName fieldName) {
    Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
    Validate.notNull(members, "Members required");
    Validate.notNull(fieldName, "Field name to remove is required");
    // Locate the field
    int i = -1;
    int toDelete = -1;
    for (final BodyDeclaration bd : members) {
        i++;
        if (bd instanceof FieldDeclaration) {
            final FieldDeclaration fieldDeclaration = (FieldDeclaration) bd;
            for (final VariableDeclarator var : fieldDeclaration.getVariables()) {
                if (var.getId().getName().equals(fieldName.getSymbolName())) {
                    toDelete = i;
                    break;
                }
            }
        }
    }
    Validate.isTrue(toDelete > -1, "Could not locate field '%s' to delete", fieldName);
    // Do removal outside iteration of body declaration members, to avoid
    // concurrent modification exceptions
    members.remove(toDelete);
}
Also used : BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) FieldDeclaration(com.github.antlrjavaparser.api.body.FieldDeclaration) VariableDeclarator(com.github.antlrjavaparser.api.body.VariableDeclarator)

Aggregations

BodyDeclaration (com.github.antlrjavaparser.api.body.BodyDeclaration)4 FieldDeclaration (com.github.antlrjavaparser.api.body.FieldDeclaration)4 VariableDeclarator (com.github.antlrjavaparser.api.body.VariableDeclarator)4 AnnotationExpr (com.github.antlrjavaparser.api.expr.AnnotationExpr)3 TypeDeclaration (com.github.antlrjavaparser.api.body.TypeDeclaration)2 ClassOrInterfaceType (com.github.antlrjavaparser.api.type.ClassOrInterfaceType)2 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)2 CommentStructure (org.springframework.roo.classpath.details.comments.CommentStructure)2 JavaType (org.springframework.roo.model.JavaType)2 ParseException (com.github.antlrjavaparser.ParseException)1 CompilationUnit (com.github.antlrjavaparser.api.CompilationUnit)1 ImportDeclaration (com.github.antlrjavaparser.api.ImportDeclaration)1 ClassOrInterfaceDeclaration (com.github.antlrjavaparser.api.body.ClassOrInterfaceDeclaration)1 ConstructorDeclaration (com.github.antlrjavaparser.api.body.ConstructorDeclaration)1 EnumConstantDeclaration (com.github.antlrjavaparser.api.body.EnumConstantDeclaration)1 EnumDeclaration (com.github.antlrjavaparser.api.body.EnumDeclaration)1 MethodDeclaration (com.github.antlrjavaparser.api.body.MethodDeclaration)1 Expression (com.github.antlrjavaparser.api.expr.Expression)1 MarkerAnnotationExpr (com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr)1 NameExpr (com.github.antlrjavaparser.api.expr.NameExpr)1