本文整理汇总了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);
}
示例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");
}
示例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);
});
}
}
示例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;
}
示例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);
});
}
}
示例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());
}
}
示例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);
}
}
示例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;
}
}
示例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;
}
示例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
);
}
示例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);
}
}
示例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();
}
示例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;
}
示例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());
}
示例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"));
}