Package japa.parser.ast.body

Examples of japa.parser.ast.body.MethodDeclaration


        cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("cn.shenyanchao.javaparser.test")));
        //create the type declaration
        ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "HelloWorld");
        ASTHelper.addTypeDeclaration(cu, type);
        //create a method
        MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
        method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
        ASTHelper.addMember(type, method);

        //add a parameter to the method
        Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 1), "args");
//        param.setVarArgs(true);
        ASTHelper.addParameter(method, param);

        //add a body to the method
        BlockStmt block = new BlockStmt();
        method.setBody(block);

        //add a statement do the method body
        NameExpr clazz = new NameExpr("System");
        FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
        MethodCallExpr call = new MethodCallExpr(field, "println");
View Full Code Here


    annotations.add(generated);
    type.setAnnotations(annotations);
    ASTHelper.addTypeDeclaration(cu, type);
    for (PropertyInfos infos : informerInfos.properties) {
      // create a method
      MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "get" + Utils.uppercaseFirst(infos.name));
      String informerTypeFor = InformerTypeFinder.getInformerTypeFor(resolvedInformers, qualifiedEnums, imports, infos);
      method.setType(new ClassOrInterfaceType(informerTypeFor));
      method.setJavaDoc(new JavadocComment(infos.generateJavadoc(informerInfos, informerTypeFor)));
      ASTHelper.addMember(type, method);
    }
   
    imports.remove(informerInfos.classPackage);
    imports.remove("java.lang");
View Full Code Here

                                        typeParameterNames).build();
                        cidBuilder.addField(field);
                    }
                }
                if (member instanceof MethodDeclaration) {
                    final MethodDeclaration castMember = (MethodDeclaration) member;
                    final MethodMetadata method = JavaParserMethodMetadataBuilder
                            .getInstance(declaredByMetadataId, castMember,
                                    compilationUnitServices, typeParameterNames)
                            .build();
                    cidBuilder.addMethod(method);
                }
                if (member instanceof ConstructorDeclaration) {
                    final ConstructorDeclaration castMember = (ConstructorDeclaration) member;
                    final ConstructorMetadata constructor = JavaParserConstructorMetadataBuilder
                            .getInstance(declaredByMetadataId, castMember,
                                    compilationUnitServices, typeParameterNames)
                            .build();
                    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,
View Full Code Here

                returnType = cit;
            }
        }

        // Start with the basic method
        final MethodDeclaration d = new MethodDeclaration();
        d.setModifiers(JavaParserUtils.getJavaParserModifier(method
                .getModifier()));
        d.setName(method.getMethodName().getSymbolName());
        d.setType(returnType);

        // Add any method-level annotations (not parameter annotations)
        final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
        d.setAnnotations(annotations);
        for (final AnnotationMetadata annotation : method.getAnnotations()) {
            JavaParserAnnotationMetadataBuilder.addAnnotationToList(
                    compilationUnitServices, annotations, annotation);
        }

        // Add any method parameters, including their individual annotations and
        // type parameters
        final List<Parameter> parameters = new ArrayList<Parameter>();
        d.setParameters(parameters);

        int index = -1;
        for (final AnnotatedJavaType methodParameter : method
                .getParameterTypes()) {
            index++;

            // Add the parameter annotations applicable for this parameter type
            final List<AnnotationExpr> parameterAnnotations = new ArrayList<AnnotationExpr>();

            for (final AnnotationMetadata parameterAnnotation : methodParameter
                    .getAnnotations()) {
                JavaParserAnnotationMetadataBuilder.addAnnotationToList(
                        compilationUnitServices, parameterAnnotations,
                        parameterAnnotation);
            }

            // Compute the parameter name
            final String parameterName = method.getParameterNames().get(index)
                    .getSymbolName();

            // Compute the parameter type
            Type parameterType = null;
            if (methodParameter.getJavaType().isPrimitive()) {
                parameterType = JavaParserUtils.getType(methodParameter
                        .getJavaType());
            }
            else {
                final NameExpr type = JavaParserUtils.importTypeIfRequired(
                        compilationUnitServices.getEnclosingTypeName(),
                        compilationUnitServices.getImports(),
                        methodParameter.getJavaType());
                final ClassOrInterfaceType cit = JavaParserUtils
                        .getClassOrInterfaceType(type);

                // Add any type arguments presented for the return type
                if (methodParameter.getJavaType().getParameters().size() > 0) {
                    final List<Type> typeArgs = new ArrayList<Type>();
                    cit.setTypeArgs(typeArgs);
                    for (final JavaType parameter : methodParameter
                            .getJavaType().getParameters()) {
                        typeArgs.add(JavaParserUtils.importParametersForType(
                                compilationUnitServices.getEnclosingTypeName(),
                                compilationUnitServices.getImports(), parameter));
                    }
                }

                // Handle arrays
                if (methodParameter.getJavaType().isArray()) {
                    final ReferenceType rt = new ReferenceType();
                    rt.setArrayCount(methodParameter.getJavaType().getArray());
                    rt.setType(cit);
                    parameterType = rt;
                }
                else {
                    parameterType = cit;
                }
            }

            // Create a Java Parser method parameter and add it to the list of
            // parameters
            final Parameter p = new Parameter(parameterType,
                    new VariableDeclaratorId(parameterName));
            p.setVarArgs(methodParameter.isVarArgs());
            p.setAnnotations(parameterAnnotations);
            parameters.add(p);
        }

        // Add exceptions which the method my throw
        if (method.getThrowsTypes().size() > 0) {
            final List<NameExpr> throwsTypes = new ArrayList<NameExpr>();
            for (final JavaType javaType : method.getThrowsTypes()) {
                final NameExpr importedType = JavaParserUtils
                        .importTypeIfRequired(
                                compilationUnitServices.getEnclosingTypeName(),
                                compilationUnitServices.getImports(), javaType);
                throwsTypes.add(importedType);
            }
            d.setThrows(throwsTypes);
        }

        // Set the body
        if (StringUtils.isBlank(method.getBody())) {
            // Never set the body if an abstract method
            if (!Modifier.isAbstract(method.getModifier())
                    && !PhysicalTypeCategory.INTERFACE
                            .equals(compilationUnitServices
                                    .getPhysicalTypeCategory())) {
                d.setBody(new BlockStmt());
            }
        }
        else {
            // There is a body.
            // We need to make a fake method that we can have JavaParser parse.
            // Easiest way to do that is to build a simple source class
            // containing the required method and re-parse it.
            final StringBuilder sb = new StringBuilder();
            sb.append("class TemporaryClass {\n");
            sb.append("  public void temporaryMethod() {\n");
            sb.append(method.getBody());
            sb.append("\n");
            sb.append("  }\n");
            sb.append("}\n");
            final ByteArrayInputStream bais = new ByteArrayInputStream(sb
                    .toString().getBytes());
            CompilationUnit ci;
            try {
                ci = JavaParser.parse(bais);
            }
            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("Method body 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 MethodDeclaration)) {
                throw new IllegalStateException(
                        "Illegal state: JavaParser did not return a method declaration correctly");
            }
            final MethodDeclaration md = (MethodDeclaration) bd;
            d.setBody(md.getBody());
        }

        // Locate where to add this method; also verify if this method already
        // exists
        for (final BodyDeclaration bd : members) {
            if (bd instanceof MethodDeclaration) {
                // Next method should appear after this current method
                final MethodDeclaration md = (MethodDeclaration) bd;
                if (md.getName().equals(d.getName())) {
                    if ((md.getParameters() == null || md.getParameters()
                            .isEmpty())
                            && (d.getParameters() == null || d.getParameters()
                                    .isEmpty())) {
                        throw new IllegalStateException("Method '"
                                + method.getMethodName().getSymbolName()
                                + "' already exists");
                    }
                    else if (md.getParameters() != null
                            && md.getParameters().size() == d.getParameters()
                                    .size()) {
                        // Possible match, we need to consider parameter types
                        // as well now
                        final MethodMetadata methodMetadata = JavaParserMethodMetadataBuilder
                                .getInstance(method.getDeclaredByMetadataId(),
View Full Code Here

      for (BodyDeclaration member : type.getMembers()) {
        if (member instanceof ClassOrInterfaceDeclaration || member instanceof EnumDeclaration) {
          getJavaMethods(methods, (TypeDeclaration)member);
        } else {
          if (member instanceof MethodDeclaration) {
            MethodDeclaration method = (MethodDeclaration)member;
            if (!ModifierSet.hasModifier(((MethodDeclaration)member).getModifiers(), ModifierSet.NATIVE)) continue;
            methods.add(createMethod(method));
          }
        }
      }
View Full Code Here

    type.setExtends(Arrays.asList(new ClassOrInterfaceType(Informer.class.getSimpleName() + "<" + informerInfos.className + ">")));
    type.setJavaDoc(new JavadocComment("\n" + "Informer for {@link " + informerInfos.className + "}\n" + "@author InformerMojos\n"));
    ASTHelper.addTypeDeclaration(cu, type);
    for (PropertyInfos infos : informerInfos.properties) {
      // create a method
      MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "get" + Utils.uppercaseFirst(infos.name));
      String informerTypeFor = InformerTypeFinder.getInformerTypeFor(resolvedInformers, qualifiedEnums, imports, infos);
      method.setType(new ClassOrInterfaceType(informerTypeFor));
      method.setJavaDoc(new JavadocComment(infos.generateJavadoc(informerInfos.className, informerTypeFor)));
      ASTHelper.addMember(type, method);
    }
   
    imports.remove(informerInfos.classPackage);
    imports.remove("java.lang");
View Full Code Here

            String name = d.getId().getName();
            addInfosFor(properties, InfosTypes.FIELD, name, type);
          }
        }
      } else if (b instanceof MethodDeclaration) {
        MethodDeclaration m = (MethodDeclaration) b;
        if(includeStaticProperties || !Modifier.isStatic(m.getModifiers())) {
          if (isGetter(m)) {
            addInfosFor(properties, InfosTypes.GETTER, m.getName(), m.getType());
          } else if (isSetter(m)) {
            addInfosFor(properties, InfosTypes.SETTER, m.getName(), m.getParameters().get(0).getType());
          }
        }
      }
    }
    return properties;
View Full Code Here

    annotations.add(generated);
    type.setAnnotations(annotations);
    ASTHelper.addTypeDeclaration(cu, type);
    for (PropertyInfos infos : informerInfos.properties) {
      // create a method
      MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "get" + Utils.uppercaseFirst(infos.name));
      String informerTypeFor = InformerTypeFinder.getInformerTypeFor(resolvedInformers, qualifiedEnums, imports, infos);
      method.setType(new ClassOrInterfaceType(informerTypeFor));
      method.setJavaDoc(new JavadocComment(infos.generateJavadoc(informerInfos, informerTypeFor)));
      ASTHelper.addMember(type, method);
    }
   
    imports.remove(informerInfos.classPackage);
    imports.remove("java.lang");
View Full Code Here

        cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("cn.shenyanchao.javaparser.test")));
        //create the type declaration
        ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "HelloWorld");
        ASTHelper.addTypeDeclaration(cu, type);
        //create a method
        MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
        method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
        ASTHelper.addMember(type, method);

        //add a parameter to the method
        Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 1), "args");
//        param.setVarArgs(true);
        ASTHelper.addParameter(method, param);

        //add a body to the method
        BlockStmt block = new BlockStmt();
        method.setBody(block);

        //add a statement do the method body
        NameExpr clazz = new NameExpr("System");
        FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
        MethodCallExpr call = new MethodCallExpr(field, "println");
View Full Code Here

     * check whether test method has exists
     * @param method
     * @return existMethod or null
     */
    public static MethodDeclaration isTestCaseExist(CompilationUnit testCU, MethodDeclaration method) {
        MethodDeclaration rtnMethodDeclaration = null;
        if (null == testCU){
            return  null;
        }
        List<TypeDeclaration> types = testCU.getTypes();
        for (TypeDeclaration type : types) {
View Full Code Here

TOP

Related Classes of japa.parser.ast.body.MethodDeclaration

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.