2010-10-15 42 views
3

如何编程得到的一份声明字段类型这样的方法中:获得字段类型的方法,在Eclipse

Foo foo = getSomeFoo(); 

如果是外地的,我可以知道元素的类型。

+0

你问如何找出由getSomeFoo()返回的对象的类?是foo.getClass()你需要什么?我不认为我理解这个问题。 – 2010-10-15 00:13:57

回答

3

您需要使用上Eclipse的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; 
    } 
});
0

通过调用foo.getClass()可以获得foo对象的类。

如果你有一个类(或对象),并希望以编程方式获取这个类的一个特定方法的返回类型,试试这个:

  • 获取Class对象的类/对象
  • 调用getMethod()方法,并得到一个Method对象回
  • 调用getReturnType()方法的Method对象
+0

如果您需要更多细节,请在Google上搜索“Java Reflection” – 2010-10-15 00:30:57

+0

我认为他的意思是从eclipse插件 – IAdapter 2010-10-15 10:52:32