com.github.javaparser.ast.CompilationUnit.getClassByName()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(14.8k)|赞(0)|评价(0)|浏览(158)

本文整理了Java中com.github.javaparser.ast.CompilationUnit.getClassByName()方法的一些代码示例,展示了CompilationUnit.getClassByName()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CompilationUnit.getClassByName()方法的具体详情如下:
包路径:com.github.javaparser.ast.CompilationUnit
类名称:CompilationUnit
方法名:getClassByName

CompilationUnit.getClassByName介绍

暂无

代码示例

代码示例来源:origin: net.sf.esfinge/classmock

public FieldImp parse(final String signature) {
  final StringBuilder sb = new StringBuilder();
  sb.append("class A {\n");
  sb.append(signature.endsWith(";") ? signature : signature.concat(";"));
  sb.append("\n}");
  final FieldImp field = new FieldImp("NOT_DEFINED", null);
  final CompilationUnit compilationUnit = JavaParser.parse(sb.toString());
  compilationUnit.getClassByName("A").ifPresent(clazz -> {
    clazz.getFields().forEach(fd -> {
      field.name(fd.getVariables().get(0).toString());
      field.type(this.getType(fd));
      field.visibility(this.getVisibility(fd));
      field.modifiers(this.getModifiers(fd));
      fd.getAnnotations().forEach(an -> this.getAnnotationField(an)
              .ifPresent(x -> field.annotation(x)));
    });
  });
  return field;
}

代码示例来源:origin: gradle.plugin.com.github.honourednihilist/gradle-kafka-deserializers

.getClassByName(info.getClassName())
.map(declaration -> declaration.getImplementedTypes()
    .stream()

代码示例来源:origin: net.sf.esfinge/classmock

public MethodImp parse(final String signature) {
  final StringBuilder sb = new StringBuilder();
  sb.append("class A {\n");
  if (!signature.contains("(")) {
    sb.append(signature.contains("()") ? signature : signature.concat("()"));
  } else {
    sb.append(signature);
  }
  if (!signature.contains("{}")) {
    sb.append(" {}");
  }
  sb.append("\n}");
  final MethodImp method = new MethodImp("NOT_DEFINED");
  final CompilationUnit compilationUnit = JavaParser.parse(sb.toString());
  compilationUnit.getClassByName("A").ifPresent(clazz -> {
    clazz.getMethods().forEach(md -> {
      method.name(md.getNameAsString());
      method.visibility(this.getVisibility(md));
      method.modifiers(this.getModifiers(md));
      method.returnType(this.getReturnType(md));
      method.exceptions(this.getExceptions(md));
      md.getAnnotations().forEach(an -> this.getAnnotationMethod(an)
              .ifPresent(x -> method.annotation(x)));
      md.getParameters().forEach(p -> this.getField(p)
              .ifPresent(x -> method.parameters().add(x)));
    });
  });
  return method;
}

代码示例来源:origin: com.github.javaparser/javaparser-symbol-solver-core

public SymbolReference<ResolvedTypeDeclaration> solve(ThisExpr node) {
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()) {
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()) {
      return SymbolReference.solved(clazz.getCorrespondingDeclaration());
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.findAncestor(CompilationUnit.class);
    if (cu.isPresent()) {
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()) {
        return SymbolReference.solved(getTypeDeclaration(classByName.get()));
      }
    }
  }
  return SymbolReference.solved(getTypeDeclaration(findContainingTypeDeclOrObjectCreationExpr(node)));
}

代码示例来源:origin: com.github.javaparser/java-symbol-solver-core

public SymbolReference<ResolvedTypeDeclaration> solve(ThisExpr node){
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()){
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()){
      return SymbolReference.solved(clazz.getCorrespondingDeclaration());
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.getAncestorOfType(CompilationUnit.class);
    if (cu.isPresent()){
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()){
        return SymbolReference.solved(getTypeDeclaration(classByName.get()));
      }
    }
  }
  return SymbolReference.solved(getTypeDeclaration(findContainingTypeDeclOrObjectCreationExpr(node)));
}

代码示例来源:origin: javaparser/javasymbolsolver

public SymbolReference<ResolvedTypeDeclaration> solve(ThisExpr node){
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()){
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()){
      return SymbolReference.solved(clazz.getCorrespondingDeclaration());
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.getAncestorOfType(CompilationUnit.class);
    if (cu.isPresent()){
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()){
        return SymbolReference.solved(getTypeDeclaration(classByName.get()));
      }
    }
  }
  return SymbolReference.solved(getTypeDeclaration(findContainingTypeDeclOrObjectCreationExpr(node)));
}

代码示例来源:origin: ftomassetti/analyze-java-code-examples

ClassOrInterfaceDeclaration classDeclaration = compilationUnitNode.getClassByName("A").get();
System.out.println(String.format("Class declaration: name=%s, nMembers=%s",
    classDeclaration.getName(), classDeclaration.getMembers().size()));

代码示例来源:origin: javaparser/javasymbolsolver

@Override
public ResolvedType visit(ThisExpr node, Boolean solveLambdas) {
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()){
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()){
      return new ReferenceTypeImpl(clazz.getCorrespondingDeclaration(),typeSolver);
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.getAncestorOfType(CompilationUnit.class);
    if (cu.isPresent()){
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()){
        return new ReferenceTypeImpl(facade.getTypeDeclaration(classByName.get()), typeSolver);
      }
    }
  }
  return new ReferenceTypeImpl(facade.getTypeDeclaration(facade.findContainingTypeDeclOrObjectCreationExpr(node)), typeSolver);
}

代码示例来源:origin: com.github.javaparser/javaparser-symbol-solver-core

@Override
public ResolvedType visit(ThisExpr node, Boolean solveLambdas) {
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()) {
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()) {
      return new ReferenceTypeImpl(clazz.getCorrespondingDeclaration(), typeSolver);
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.findAncestor(CompilationUnit.class);
    if (cu.isPresent()) {
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()) {
        return new ReferenceTypeImpl(facade.getTypeDeclaration(classByName.get()), typeSolver);
      }
    }
  }
  return new ReferenceTypeImpl(facade.getTypeDeclaration(facade.findContainingTypeDeclOrObjectCreationExpr(node)), typeSolver);
}

代码示例来源:origin: com.github.javaparser/java-symbol-solver-core

@Override
public ResolvedType visit(ThisExpr node, Boolean solveLambdas) {
  // If 'this' is prefixed by a class eg. MyClass.this
  if (node.getClassExpr().isPresent()){
    // Get the class name
    String className = node.getClassExpr().get().toString();
    // Attempt to resolve using a typeSolver
    SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className);
    if (clazz.isSolved()){
      return new ReferenceTypeImpl(clazz.getCorrespondingDeclaration(),typeSolver);
    }
    // Attempt to resolve locally in Compilation unit
    Optional<CompilationUnit> cu = node.getAncestorOfType(CompilationUnit.class);
    if (cu.isPresent()){
      Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className);
      if (classByName.isPresent()){
        return new ReferenceTypeImpl(facade.getTypeDeclaration(classByName.get()), typeSolver);
      }
    }
  }
  return new ReferenceTypeImpl(facade.getTypeDeclaration(facade.findContainingTypeDeclOrObjectCreationExpr(node)), typeSolver);
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
public void issue257() throws FileNotFoundException {
  String pathToSourceFile = adaptPath("src/test/resources/issue257/A.java.txt");
  CompilationUnit cu = JavaParser.parse(new File(pathToSourceFile));
  Statement statement = cu.getClassByName("A").get().getMethodsByName("run").get(0).getBody().get().getStatement(0);
  ExpressionStmt expressionStmt = (ExpressionStmt)statement;
  Expression expression = expressionStmt.getExpression();
  JavaParserFacade.get(typeSolver).getType(expression);
}

代码示例来源:origin: ftomassetti/analyze-java-code-examples

public static void main(String[] args) throws FileNotFoundException {
    // The directory where we store the examples
    String pathToExamplesDir = "." + separator + "src"
        + separator + "main" + separator + "resources";
    // Parse the code of an entire source file, a.k.a. a Compilation Unit
    CompilationUnit compilationUnitNode = JavaParser.parse(new File(pathToExamplesDir
        + separator + "ASimpleClass.java"));
    printCompilationUnit("My original class", compilationUnitNode);

    // Modifying the name of the class
    compilationUnitNode.getClassByName("ASimpleClass").get()
        .setName("MyRenamedClass");
    printCompilationUnit("Renamed class", compilationUnitNode);

    // Adding a method: we add a setter
    MethodDeclaration setter = compilationUnitNode
        .getClassByName("MyRenamedClass").get()
        .addMethod("setAField", Modifier.PUBLIC);
    setter.addParameter("boolean", "aField");
    setter.getBody().get().getStatements().add(new ExpressionStmt(
        new AssignExpr(
          new FieldAccessExpr(new ThisExpr(),"aField"),
        new NameExpr("aField"),
        AssignExpr.Operator.ASSIGN
    )));
    printCompilationUnit("With a setter", compilationUnitNode);
  }
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
public void issue113superClassIsResolvedCorrectly() throws FileNotFoundException {
  String pathToSourceFile = adaptPath("src/test/resources/issue113/com/foo/Widget.java");
  CompilationUnit cu = JavaParser.parse(new File(pathToSourceFile));
  JavaParserClassDeclaration jssExtendedWidget = new JavaParserClassDeclaration(cu.getClassByName("Widget").get(), typeSolver);
  ResolvedReferenceType superClass = jssExtendedWidget.getSuperClass();
  assertEquals("com.foo.base.Widget", superClass.getQualifiedName());
}

代码示例来源:origin: YeDaxia/JApiDocs

@Test
  public void test_parseGenericClassNode(){
    File resultJavaFile = Projects.getTestJavaFile(GenericResult.class);

    ParseUtils.compilationUnit(resultJavaFile).getChildNodesByType(MethodDeclaration.class).forEach(md->{
       md.getType();
    });

    ParseUtils.compilationUnit(resultJavaFile).getClassByName("GenericResult")
        .ifPresent(classDeclaration -> {
          NodeList<TypeParameter> typeParameters = classDeclaration.getTypeParameters();
          for(int i = 0, len = typeParameters.size(); i != len; i++){
            System.out.println(typeParameters.get(i).getName());
          }
        });
  }
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
  public void resolveArrayType() throws ParseException {
    TypeSolver typeSolver = new ReflectionTypeSolver();

    CompilationUnit cu = parseSample("SymbolResolverExample");
    new JavaSymbolSolver(typeSolver).inject(cu);

    MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMethods().get(0);
    ResolvedType resolvedType = methodDeclaration.getType().resolve();
    assertEquals("A[]", resolvedType.describe());
  }
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
  public void verifyAnArrayAccessExprTypeIsCalculatedProperly() {
    String code = "class A { String[] arrSQL; String toExamine = arrSQL[1]; }";
    FieldDeclaration field = JavaParser.parse(code).getClassByName("A").get().getFieldByName("toExamine").get();

    ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(field.getVariables().get(0).getInitializer().get());
    assertEquals(true, type.isReferenceType());
    assertEquals("java.lang.String", type.asReferenceType().getQualifiedName());
  }
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test(expected = UnsolvedSymbolException.class)
public void aClassInDefaultPackageCanBeAccessedFromOutsideTheDefaultPackageImportingIt() {
  String code = "package myPackage; import B; class A extends B {}";
  MemoryTypeSolver memoryTypeSolver = new MemoryTypeSolver();
  memoryTypeSolver.addDeclaration("B", new MyClassDeclaration("B"));
  ClassOrInterfaceType jpType = JavaParser.parse(code).getClassByName("A").get().getExtendedTypes(0);
  ResolvedType resolvedType = JavaParserFacade.get(memoryTypeSolver).convertToUsage(jpType);
  assertEquals("B", resolvedType.asReferenceType().getQualifiedName());
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
public void aClassInDefaultPackageCanBeAccessedFromTheDefaultPackage() {
  String code = "class A extends B {}";
  MemoryTypeSolver memoryTypeSolver = new MemoryTypeSolver();
  memoryTypeSolver.addDeclaration("B", new MyClassDeclaration("B"));
  ClassOrInterfaceType jpType = JavaParser.parse(code).getClassByName("A").get().getExtendedTypes(0);
  ResolvedType resolvedType = JavaParserFacade.get(memoryTypeSolver).convertToUsage(jpType);
  assertEquals("B", resolvedType.asReferenceType().getQualifiedName());
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test(expected = UnsolvedSymbolException.class)
  public void aClassInDefaultPackageCanBeAccessedFromOutsideTheDefaultPackageWithoutImportingIt() {
    String code = "package myPackage; class A extends B {}";
    MemoryTypeSolver memoryTypeSolver = new MemoryTypeSolver();
    memoryTypeSolver.addDeclaration("B", new MyClassDeclaration("B"));

    ResolvedType resolvedType = JavaParserFacade.get(memoryTypeSolver).convertToUsage(JavaParser.parse(code).getClassByName("A").get().getExtendedTypes(0));
    assertEquals("B", resolvedType.asReferenceType().getQualifiedName());
  }
}

代码示例来源:origin: javaparser/javasymbolsolver

@Test
public void resolveMethodDeclaration() throws ParseException {
  TypeSolver typeSolver = new ReflectionTypeSolver();
  CompilationUnit cu = parseSample("SymbolResolverExample");
  new JavaSymbolSolver(typeSolver).inject(cu);
  MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMethods().get(0);
  ResolvedMethodDeclaration resolvedMethodDeclaration = methodDeclaration.resolve();
  assertEquals("foo", resolvedMethodDeclaration.getName());
  assertEquals("A[]", resolvedMethodDeclaration.getReturnType().describe());
  assertEquals("java.lang.String[]", resolvedMethodDeclaration.getParam(0).getType().describe());
  assertEquals("int[]", resolvedMethodDeclaration.getParam(1).getType().describe());
}

相关文章