2015-02-07 58 views
2

是否可以从匿名类获取最终参数值?使用反射或其他什么?从anonynous类获取参数

这个例子当然所有组成:

final String x = "Param1"; 
final String y = "Param2"; 
ITest<String> iTest = new ITest<String>() { 

    @Override 
    public String execute() { 
     return t.testMethod(x, y); 
    } 

}; 
// Get values or x and y from iTest here? 
+1

感。你没有做任何事。 – 2015-02-07 00:12:15

+0

您可以创建实例变量来保留传递的参数。 – 2015-02-07 00:16:24

+0

@MalikBrahimi你能解释一下吗? – KTrum 2015-02-07 00:18:14

回答

1

因此,这是你的代码:

ITest<String> iTest = new ITest<String>() { 

    @Override 
    public String execute() { 
     return testMethod(x, y); 
    } 

}; 

尝试定义ITest像这样:

public class ITest { 
    int x; 
    int y; 

    public testMethod(int x, int y) { 
     this.x = x; this.y = y; 
    } 

    // execute somewhere 
} 
+0

这似乎工作。但是没有其他办法可以实现你的想法?'不改变ITest – KTrum 2015-02-07 00:36:20

+0

我不这么认为。 – 2015-02-07 00:37:46

1

我没有尝试这样做我自己,但我认为,xy的值复制到该匿名类的实例自动生成的字段。试试这个:

for (Field field : iTest.getClass().getDeclaredFields()) { 
    field.setAccessible(true); 
    System.out.println(field.getName() + ": " + field.get(iTest)); 
} 
+0

我也这么认为,但可悲的是我只得到了运行此代码的外部类的引用 – KTrum 2015-02-07 00:17:45