本文整理汇总了Java中com.github.javaparser.ast.CompilationUnit类的典型用法代码示例。如果您正苦于以下问题:Java CompilationUnit类的具体用法?Java CompilationUnit怎么用?Java CompilationUnit使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CompilationUnit类属于com.github.javaparser.ast包,在下文中一共展示了CompilationUnit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getTypeName
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
@Override
protected String getTypeName(CompilationUnit compilationUnit, int index) {
ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
ClassOrInterfaceType extendedType = extendedTypes.get(index);
String typeSimpleName = extendedType.getName().getIdentifier();
Optional<ClassOrInterfaceType> scope = extendedType.getScope();
String typeName;
if (scope.isPresent()) {
String typePackageName = scope.get().toString();
typeName = String.format("%s.%s", typePackageName, typeSimpleName);
} else {
typeName = typeSimpleName;
}
return typeName;
}
示例2: analyze
import com.github.javaparser.ast.CompilationUnit; //导入依赖的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;
}
示例3: brewJava
import com.github.javaparser.ast.CompilationUnit; //导入依赖的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);
}
示例4: createCompletionProvider
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
/**
* A method to create a completion provider for the auto-complete functionality
* @param activeFile a parameter to take the active file to create auto complete for that file
* @return CompletionProvider object to create words which will be auto-completed
* @throws ParseProblemException
* @throws FileNotFoundException
*/
private CompletionProvider createCompletionProvider(File activeFile) throws ParseProblemException,FileNotFoundException
{
DefaultCompletionProvider provider = new DefaultCompletionProvider();
FileInputStream in = new FileInputStream(activeFile.getAbsolutePath());
CompilationUnit cu = JavaParser.parse(in);
FieldVisitor namesOfVariables = new FieldVisitor( cu, null);
namesOfVariables.visit(cu,null);
for( int i = 0; i < namesOfVariables.getNamesOfVariables().size(); i++)
{
provider.addCompletion(new BasicCompletion(provider, namesOfVariables.getNamesOfVariables().get(i), namesOfVariables.getDescOfVariables().get(i) ));
}
return provider;
}
示例5: matches
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
@Override
public boolean matches(Object item) {
Optional<ClassOrInterfaceDeclaration> referenceClass = compilationUnit.getClassByName(className);
Optional<ClassOrInterfaceDeclaration> actualClass = ((CompilationUnit) item).getClassByName(className);
if (referenceClass.isPresent() && actualClass.isPresent()) {
Optional<ConstructorDeclaration> referenceConstructor = referenceClass.get().getConstructorByParameterTypes(params);
Optional<ConstructorDeclaration> actualConstructor = actualClass.get().getConstructorByParameterTypes(params);
return referenceConstructor.isPresent()
&& actualConstructor.isPresent()
&& referenceConstructor.get().equals(actualConstructor.get());
}
return false;
}
示例6: testPackagelessEndpoint
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
@Test
public void testPackagelessEndpoint() throws FileNotFoundException {
String testFile = packageLessTestFile;
CompilationUnit cu = generateCompilationUnitFromFile(testFile);
logger.debug("Running visitors...");
// Visit and print the methods' names
cu.accept(new SpringAnnotationAnalyzer(), cu.getPackageDeclaration());
// Get endpoints we've found
ArrayList<Endpoint> endpoints = SpringAPIIdentifier.getEndpoints();
//Just be sure we got something from the file....
//public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { ...
assertEquals("name", endpoints.get(0).getParams().get(0).getHttpParameterName());
}
示例7: testGetClassNameFromMethod
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
@Test
public void testGetClassNameFromMethod() {
//Code from: https://github.com/javaparser/javaparser/wiki/Manual
CompilationUnit cu = new CompilationUnit();
// set the package
cu.setPackageDeclaration(new PackageDeclaration(Name.parse("com.aspectsecurity.example")));
// or a shortcut
cu.setPackageDeclaration("com.aspectsecurity.example");
// create the type declaration
ClassOrInterfaceDeclaration type = cu.addClass("GeneratedClass");
// create a method
EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC);
MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), "main");
modifiers.add(Modifier.STATIC);
method.setModifiers(modifiers);
type.addMember(method);
assertEquals("GeneratedClass", saa.getClassNameFromMethod(method));
}
示例8: initializeNodeModifiers
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
/***
* This method sets the modifiers into a given Class, Interface, and Enumeration
*/
public void initializeNodeModifiers(AbstractStructure abstractStructure) {
try {
CompilationUnit compilationUnit = abstractStructure.getCompilationUnit();
if(abstractStructure instanceof ClassStructure || abstractStructure instanceof InterfaceStructure) {
compilationUnit.getChildNodesByType(ClassOrInterfaceDeclaration.class).stream().forEach(c -> {
abstractStructure.setAccessModifiers(castStringToModifiers(c.getModifiers().toString()));
});
} else if(abstractStructure instanceof EnumerationStructure) {
compilationUnit.getChildNodesByType(EnumDeclaration.class).stream().forEach(c -> {
abstractStructure.setAccessModifiers(castStringToModifiers(c.getModifiers().toString()));
});
}
} catch (Exception e) {
System.out.println("Error occured while opening the given file: " + e.getMessage());
}
}
示例9: saveFile
import com.github.javaparser.ast.CompilationUnit; //导入依赖的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());
}
}
示例10: getPackageNmae
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
public static String getPackageNmae(File f) {
if (f == null || !f.exists())
return "";
if (f.getName().endsWith(".java")) {
CompilationUnit parse;
try {
parse = com.github.javaparser.JavaParser.parse(f, "utf-8");
return GargoyleJavaParser.getPackageName(parse);
} catch (ParseException | IOException e) {
LOGGER.error(ValueUtil.toString(e));
}
}
return "";
}
示例11: getPackageName
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
/********************************
* 작성일 : 2016. 7. 14. 작성자 : KYJ
*
*
* @param javaFile
* @param converter
* @return
* @throws FileNotFoundException
* @throws IOException
* @throws ParseException
********************************/
public static String getPackageName(File javaFile, FileCheckHandler<String> converter)
throws FileNotFoundException, IOException, ParseException {
String packageName = null;
if (javaFile == null) {
packageName = converter.ifNull();
} else if (!javaFile.exists())
packageName = converter.notExists();
else if (javaFile.isFile()) {
CompilationUnit cu = getCompileUnit(javaFile);
packageName = getPackageName(cu);
}
return packageName;
}
示例12: findTypeOfFirstPart
import com.github.javaparser.ast.CompilationUnit; //导入依赖的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;
}
}
示例13: extractClassName
import com.github.javaparser.ast.CompilationUnit; //导入依赖的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;
}
示例14: calculate
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
public void calculate(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, CompilationUnit compilationUnit) {
List<AnnotationExpr> annotations = classOrInterfaceDeclaration.getAnnotations();
for (AnnotationExpr annotation : annotations) {
String annotationName = annotation.getNameAsString();
String annotationPackageName = annotation
.findCompilationUnit()
.flatMap(CompilationUnit::getPackageDeclaration)
.flatMap(pkg -> Optional.of(pkg.getNameAsString())).orElse("???");
if (typeDao.exist(annotationName, annotationPackageName)) { // JDK annotations are not indexed
int annotationId = typeDao.getId(annotationName, annotationPackageName);
int typeId = typeDao.getId(classOrInterfaceDeclaration.getNameAsString(), compilationUnit.getPackageDeclaration().get().getNameAsString());
annotatedWithDao.save(new AnnotatedWith(typeId, annotationId));
}
}
}
示例15: calculate
import com.github.javaparser.ast.CompilationUnit; //导入依赖的package包/类
public void calculate(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, CompilationUnit compilationUnit) {
List<ClassOrInterfaceType> implementedInterfaces = classOrInterfaceDeclaration.getImplementedTypes();
for (ClassOrInterfaceType implementedInterface : implementedInterfaces) {
String implementedInterfaceName = implementedInterface.getNameAsString();
String implementedInterfacePackageName = implementedInterface
.findCompilationUnit()
.flatMap(CompilationUnit::getPackageDeclaration)
.flatMap(pkg -> Optional.of(pkg.getNameAsString())).orElse("???");
if (typeDao.exist(implementedInterfaceName, implementedInterfacePackageName)) { // JDK interfaces are not indexed
int interfaceId = typeDao.getId(implementedInterfaceName, implementedInterfacePackageName);
String cuPackageName = compilationUnit.getPackageDeclaration().get().getNameAsString();
int nbClasses = typeDao.count(classOrInterfaceDeclaration.getNameAsString(), cuPackageName);
if (nbClasses > 1) {
System.err.println("More than one class having the same name '" + classOrInterfaceDeclaration.getName() + "' and package '" + cuPackageName + "'");
} else {
int classId = typeDao.getId(classOrInterfaceDeclaration.getNameAsString(), cuPackageName);
implementsDao.save(new Implements(classId, interfaceId));
}
}
}
}