views:

25

answers:

2

How do I programmatically get the field type from a statement inside a method like this :

Foo foo = getSomeFoo();

If it is field, I can know the type of the element.

A: 

You can get the class of the foo object by calling foo.getClass().

If you have a class (or object) and want to programmatically get the return type for a particular method on that class, try this:

  • Get the Class object for the class/object
  • Call the getMethod() method and get a Method object back
  • Call the getReturnType() method on the Method object
Jim Tough
If you need more details on this, search Google for "Java Reflection"
Jim Tough
i think he means from eclipse plugin
01
+2  A: 

You need to use Eclipse's AST

ICompilationUnit icu = ...

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setSource(icu);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
    @Override
    public boolean visit(VariableDeclarationStatement node) {
        System.out.println("node=" + node);
        System.out.println("node.getType()=" + node.getType());
        return true;
    }
});
01