문제

I found out that Java Literals are syntactic representations of boolean, character, numeric, or string data.

My question is how to find literals in a java class programmatically?

If any one can provide me directions on how to achieve this ,that will be a great help.

도움이 되었습니까?

해결책

You should use a Java code parser, such as the ASTParser included in the Eclipse JDT tooling.

// Create the Java parser and parse the source code into an abstract syntax tree
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(sourceCodeString.toCharArray());
CompilationUnit result = (CompilationUnit) parser.createAST(null);
result.accept(new ASTVisitor() {
  public boolean visit(NumberLiteral n) {
    System.out.println("Found number literal in source code: " + n.getToken());
  }
});

You can then navigate the AST (abstract syntax tree) and extract what interests you.

Find longer examples here or here.

You could also look at the source code of tools doing what you want to do, e.g. PMD or Findbugs (although the latter operates on compiled classes, not on source code).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top