Question

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.

Était-ce utile?

La solution

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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top