當前位置: 首頁>>代碼示例>>Java>>正文


Java JavaParser類代碼示例

本文整理匯總了Java中com.github.javaparser.JavaParser的典型用法代碼示例。如果您正苦於以下問題:Java JavaParser類的具體用法?Java JavaParser怎麽用?Java JavaParser使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JavaParser類屬於com.github.javaparser包,在下文中一共展示了JavaParser類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: brewJava

import com.github.javaparser.JavaParser; //導入依賴的package包/類
public static void brewJava(File rFile, File outputDir, String packageName, String className)
    throws Exception {
  CompilationUnit compilationUnit = JavaParser.parse(rFile);
  TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

  TypeSpec.Builder result =
      TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);

  for (Node node : resourceClass.getChildrenNodes()) {
    if (node instanceof TypeDeclaration) {
      addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (TypeDeclaration) node);
    }
  }

  JavaFile finalR = JavaFile.builder(packageName, result.build())
      .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
      .build();

  finalR.writeTo(outputDir);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:FinalRClassBuilder.java

示例2: setUp

import com.github.javaparser.JavaParser; //導入依賴的package包/類
@BeforeEach
void setUp() throws IOException {
    String source = "package com.example; " +
            "import org.dataj.Data; " +
            "import javax.annotation.Nonnull;" +
            "import javax.annotation.Nullable;" +
            "@Data class NullableFields { @Nonnull String name; @Nullable Integer age; }";

    Compilation compilation = javac()
            .withProcessors(new AnnotationProcessor())
            .compile(
                    JavaFileObjects.forSourceString("NullableFields", source)
            );

    JavaFileObject outputFile = compilation.generatedSourceFile("com.example.NullableFieldsData").get();
    actualSource = JavaParser.parse(outputFile.openInputStream());
    referenceSource = JavaParser.parseResource("NullableFieldsData.java");
}
 
開發者ID:alek-sys,項目名稱:dataj,代碼行數:19,代碼來源:NullableFieldsTest.java

示例3: addAttributesToCompilationUnit

import com.github.javaparser.JavaParser; //導入依賴的package包/類
/**
 * It adds all the attributes need to be added to the existing compilation unit.
 */
private void addAttributesToCompilationUnit() {
    if(attributesToBeAdded.size() > 0) {
        ClassOrInterfaceDeclaration type = getFileType();

        attributesToBeAdded.stream().forEach(attribute -> {
            EnumSet<Modifier> modifiers = null;
            for (Modifier modifier : attribute.getAccessModifiers()) {
                modifiers = EnumSet.of(modifier);
            }

            VariableDeclarator vd = new VariableDeclarator(JavaParser.parseType(attribute.getDataType()), attribute.getName());
            FieldDeclaration fd = new FieldDeclaration();
            fd.setModifiers(modifiers);
            fd.addVariable(vd);

            type.addMember(fd);
        });
    }
}
 
開發者ID:kaanburaksener,項目名稱:octoBubbles,代碼行數:23,代碼來源:NodeViewParser.java

示例4: analyze

import com.github.javaparser.JavaParser; //導入依賴的package包/類
public List<EntityField> analyze(File source) throws IOException, ParseException {
    List<EntityField> entityFields = new ArrayList<>();
    CompilationUnit cu = JavaParser.parse(source);
    cu.accept(new VoidVisitorAdapter<List<EntityField>>() {
        @Override
        public void visit(FieldDeclaration fd, List<EntityField> f) {
            if (fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Column"))) {
                Class<?> type = null;
                switch (fd.getType().toString()) {
                    case "String": type = String.class; break;
                    case "Long": type = Long.class; break;
                    case "Integer": type = Integer.class; break;
                    case "boolean": type = boolean.class; break;
                }
                if (type == null) return;
                f.add(new EntityField(
                        fd.getVariables().get(0).getId().getName(),
                        type,
                        fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Id"))));
            }
        }
    }, entityFields);

    return entityFields;
}
 
開發者ID:kawasima,項目名稱:enkan,代碼行數:26,代碼來源:EntitySourceAnalyzer.java

示例5: addAttributesToCompilationUnit

import com.github.javaparser.JavaParser; //導入依賴的package包/類
/**
 * It adds all the attributes need to be added to the existing compilation unit.
 */
private void addAttributesToCompilationUnit() {
    if(attributesToBeAdded.size() > 0) {
        ClassOrInterfaceDeclaration type = getFileType();

        attributesToBeAdded.stream().forEach(attribute -> {
            EnumSet<Modifier> modifiers = null;
            for (Modifier modifier : attribute.getAccessModifiers()) {
                modifiers = EnumSet.of(modifier);
            }

            VariableDeclarator vd = new VariableDeclarator(JavaParser.parseType(attribute.getDataType()), attribute.getName());
            FieldDeclaration fd = new FieldDeclaration();
            fd.setModifiers(modifiers);
            fd.addVariable(vd);

            type.addMember(fd);
            ((ClassStructure)existingAbstractStructure).addAttribute(attribute);
        });
    }
}
 
開發者ID:kaanburaksener,項目名稱:octoBubbles,代碼行數:24,代碼來源:NodeViewScratchParser.java

示例6: saveFile

import com.github.javaparser.JavaParser; //導入依賴的package包/類
private void saveFile(File file){
    try {
        String fileName = file.getName();
        Path javaFilePath = Paths.get(PATH, fileName);

        if (!Files.exists(javaFilePath)) {
            Files.createFile(javaFilePath);
            FileInputStream in = new FileInputStream(file);
            CompilationUnit compilationUnit = JavaParser.parse(in);
            compilationUnit.setPackageDeclaration(PACKAGE_NAME);

            try (BufferedWriter writer = Files.newBufferedWriter(javaFilePath, StandardCharsets.UTF_8)) {
                writer.write(compilationUnit.toString());
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }
        }
    } catch (Exception e) {
        System.out.println("Error occured while opening the given file: " + e.getMessage());
    }
}
 
開發者ID:kaanburaksener,項目名稱:octoBubbles,代碼行數:22,代碼來源:TabController.java

示例7: createFile

import com.github.javaparser.JavaParser; //導入依賴的package包/類
protected void createFile(String withPackageName,
                          List<FieldInfo> withFields,
                          String withEntrySeparator,
                          String withValueDelimiterPrefix,
                          String withValueDelimiterSuffix,
                          String withKeyValueSeparator) throws Exception {

    String fileContents = victim.createALogFormatEnforcer(
            withPackageName,
            withFields,
            withEntrySeparator,
            withValueDelimiterPrefix,
            withValueDelimiterSuffix,
            withKeyValueSeparator
    );

    try (ByteArrayInputStream in = new ByteArrayInputStream(fileContents.getBytes())) {
        compilationUnit = JavaParser.parse(in);
    }
}
 
開發者ID:leandronunes85,項目名稱:log-format-enforcer,代碼行數:21,代碼來源:AbstractTest.java

示例8: findTypeOfFirstPart

import com.github.javaparser.JavaParser; //導入依賴的package包/類
protected ResultType findTypeOfFirstPart( String code ) {
    int lastDot = code.lastIndexOf( '.' );
    if ( lastDot > 0 ) {
        String lastPart = code.substring( lastDot, code.length() );
        if ( !lastPart.equals( ".class" ) ) {
            code = code.substring( 0, lastDot );
        }
    }
    code = code.trim();
    if ( !code.startsWith( "return " ) )
        code = "return " + code;
    if ( !code.endsWith( ";" ) )
        code += ";";

    String classCode = generateClass( context, code );

    try {
        CompilationUnit cu = JavaParser.parse( new StringReader( classCode ), false );
        return new LastStatementTypeDiscoverer(
                context.getImports(), context.getClassLoaderContext().orElse( null ) )
                .discover( cu );
    } catch ( Throwable e ) {
        return ResultType.VOID;
    }
}
 
開發者ID:renatoathaydes,項目名稱:osgiaas,代碼行數:26,代碼來源:OsgiaasJavaAutocompleter.java

示例9: extractClassName

import com.github.javaparser.JavaParser; //導入依賴的package包/類
@Nullable
private static String extractClassName( String code, PrintStream err ) {
    InputStream inputStream = new ByteArrayInputStream( code.getBytes( StandardCharsets.UTF_8 ) );
    try {
        CompilationUnit compilationUnit = JavaParser.parse( inputStream );
        List<TypeDeclaration> types = compilationUnit.getTypes();
        if ( types.size() == 1 ) {
            String simpleType = types.get( 0 ).getName();
            return Optional.ofNullable( compilationUnit.getPackage() )
                    .map( PackageDeclaration::getPackageName )
                    .map( it -> it + "." + simpleType )
                    .orElse( simpleType );
        } else if ( types.size() == 0 ) {
            err.println( "No class definition found" );
        } else {
            err.println( "Too many class definitions found. Only one class can be defined at a time." );
        }
    } catch ( ParseException e ) {
        // ignore error, let the compiler provide an error message
        return "Err";
    }

    return null;
}
 
開發者ID:renatoathaydes,項目名稱:osgiaas,代碼行數:25,代碼來源:JavaCommand.java

示例10: setUp

import com.github.javaparser.JavaParser; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
    SourceWriter sourceWriter = (packageName, simpleClassName, source) -> {
        try {
            JavaParser.parse(new StringReader(source), true);
        } catch (ParseException e) {
            // Source code failed to parse.  Throw an exception that will cause the test to fail.
            throw new RuntimeException("Failed to parse generated source code", e);
        }
    };
    PortletTypeDescriptor descriptor = new PortletTypeDescriptor(
            "edu.stanford.protege.MyPortlet",
            "MyPortlet",
            "edu.stanford.protege",
            "my.portlet.id",
            "My Portlet\"\"!",
            "My amazing portlet.\n(Does all \"sorts\" of things)");
    PortletModuleDescriptor moduleDescriptorA = new PortletModuleDescriptor("edu.stanford.protege.MyPortletModuleA");
    PortletModuleDescriptor moduleDescriptorB = new PortletModuleDescriptor("edu.stanford.protege.MyPortletModuleB");
    codeGenerator = new WebProtegeCodeGeneratorVelocityImpl(
            Collections.singleton(descriptor),
            Sets.newHashSet(moduleDescriptorA, moduleDescriptorB),
            sourceWriter
    );
}
 
開發者ID:protegeproject,項目名稱:webprotege-maven-plugin,代碼行數:26,代碼來源:CodeGenerator_TestCase.java

示例11: main

import com.github.javaparser.JavaParser; //導入依賴的package包/類
public static void main( String[] args )
{
    CompilationUnit cu;
    MethodVisitor mv = new MethodVisitor();
    try{
    	
        BufferedReader bIn = new BufferedReader(new InputStreamReader(System.in));
        String input = "class dummy{\n";
        String s;
        while ((s = bIn.readLine()) != null)
        {
        	input += s + "\n";
        }
        input = input + "\n}";
    	cu = JavaParser.parse(new StringReader(input));
    	mv.visit(cu, null);            
    } catch (Exception e) {
    	System.err.println(e.getMessage());
    	System.exit(1);
    }
    
}
 
開發者ID:shashanksingh28,項目名稱:code-similarity,代碼行數:23,代碼來源:App.java

示例12: getClassDeclaration

import com.github.javaparser.JavaParser; //導入依賴的package包/類
private static ClassOrInterfaceDeclaration getClassDeclaration(File file) throws ParseException, IOException {
    final CompilationUnit compilationUnit = JavaParser.parse(file);
    final String filename = file.getName();
    final String className = filename.replaceAll("(.*)\\.java$", "$1");

    if (className.length() == file.getName().length()) {
        throw new IllegalStateException("Couldn't extract [Java] class name from filename: " + filename);
    }

    Optional<ClassOrInterfaceDeclaration> classDeclaration = compilationUnit.getTypes().stream()
            .filter(ClassOrInterfaceDeclaration.class::isInstance)
            .map(ClassOrInterfaceDeclaration.class::cast)
            .filter(declaration -> declaration.getName().equals(className))
            .findFirst();

    assertThat("class " + className + " generated", classDeclaration.isPresent(), is(true));

    return classDeclaration.get();
}
 
開發者ID:hubrick,項目名稱:raml-maven-plugin,代碼行數:20,代碼來源:SpringWebGeneratorMojoTest.java

示例13: readSource

import com.github.javaparser.JavaParser; //導入依賴的package包/類
public CompilationUnit readSource() throws FileNotFoundException {
    File file = new File(this.filePath);
    if (!file.exists()) {
        throw new FileNotFoundException("try parse a not exist source file: " + this.filePath);
    }
    
    this.filename = file.getName();

    try {
        CompilationUnit result = JavaParser.parse(file, "UTF-8", false);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:ragnraok,項目名稱:JParserUtil,代碼行數:17,代碼來源:JavaSourceReader.java

示例14: testGetAllGenericFields

import com.github.javaparser.JavaParser; //導入依賴的package包/類
@Test
public void testGetAllGenericFields() throws IOException, ParseException {
    TypeSolver typeSolver = new ReflectionTypeSolver();

    CompilationUnit cu = JavaParser.parse(adaptPath(new File("src/test/resources/GenericFields.java.txt")));
    JavaParserClassDeclaration classDeclaration = new JavaParserClassDeclaration(Navigator.demandClass(cu, "CB"), typeSolver);

    assertEquals(3, classDeclaration.getAllFields().size());

    ReferenceTypeImpl rtClassDeclaration = new ReferenceTypeImpl(classDeclaration, typeSolver);

    assertEquals("s", classDeclaration.getAllFields().get(0).getName());
    assertEquals(string, classDeclaration.getAllFields().get(0).getType());
    assertEquals(string, rtClassDeclaration.getFieldType("s").get());

    assertEquals("t", classDeclaration.getAllFields().get(1).getName());
    assertEquals("java.util.List<java.lang.Boolean>", classDeclaration.getAllFields().get(1).getType().describe());
    assertEquals(listOfBoolean, rtClassDeclaration.getFieldType("t").get());

    assertEquals("i", classDeclaration.getAllFields().get(2).getName());
    assertEquals(ResolvedPrimitiveType.INT, classDeclaration.getAllFields().get(2).getType());
    assertEquals(ResolvedPrimitiveType.INT, rtClassDeclaration.getFieldType("i").get());
}
 
開發者ID:javaparser,項目名稱:javasymbolsolver,代碼行數:24,代碼來源:JavaParserClassDeclarationTest.java

示例15: testHasDirectlyAnnotation

import com.github.javaparser.JavaParser; //導入依賴的package包/類
@Test
public void testHasDirectlyAnnotation() throws IOException, ParseException {
    TypeSolver typeSolver = new ReflectionTypeSolver();

    CompilationUnit cu = JavaParser.parse(adaptPath(new File("src/test/resources/Annotations.java.txt")));

    JavaParserClassDeclaration ca = new JavaParserClassDeclaration(Navigator.demandClass(cu, "CA"), typeSolver);
    assertEquals(true, ca.hasDirectlyAnnotation("foo.bar.MyAnnotation"));
    assertEquals(false, ca.hasDirectlyAnnotation("foo.bar.MyAnnotation2"));
    assertEquals(false, ca.hasDirectlyAnnotation("MyAnnotation"));
    assertEquals(false, ca.hasDirectlyAnnotation("foo.bar.MyUnexistingAnnotation"));

    JavaParserClassDeclaration cb = new JavaParserClassDeclaration(Navigator.demandClass(cu, "CB"), typeSolver);
    assertEquals(false, cb.hasDirectlyAnnotation("foo.bar.MyAnnotation"));
    assertEquals(true, cb.hasDirectlyAnnotation("foo.bar.MyAnnotation2"));
    assertEquals(false, cb.hasDirectlyAnnotation("MyAnnotation"));
    assertEquals(false, cb.hasDirectlyAnnotation("foo.bar.MyUnexistingAnnotation"));
}
 
開發者ID:javaparser,項目名稱:javasymbolsolver,代碼行數:19,代碼來源:JavaParserClassDeclarationTest.java


注:本文中的com.github.javaparser.JavaParser類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。