是否可以从匿名类中获取最终参数值?使用反射或其他任何东西?
这个例子当然是全部组成的:
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?
答案 0 :(得分:1)
我自己没有尝试过,但我相信x
和y
的值会被复制到匿名类实例中的自动生成字段中。试试这个:
for (Field field : iTest.getClass().getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName() + ": " + field.get(iTest));
}
答案 1 :(得分: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
}