我有这样的代码:
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
//some codes here
//if I use "this" keyword, it refers to the handler, but how can I get a reference to the textbox?
});
}
};
问题嵌入在该职位中。
修改
关于答案,预定义参考的创建适用于这种情况,但这显然丢失(或至少减少)匿名对象/功能的好处。
我希望找到一种不创建新引用的方法。而只是从该范围获得参考。
在所有答案之后,这是一个结论:
obj.getClass()
有效,但getMethods()
或getEnclosingClass()
等其他人无效。答案 0 :(得分:3)
TextBox txt = new TextBox(){
public void onLoad(){
final TextBox finalThis = this;
this.addFocusHandler(new FocusHandler(){
finalThis.doSomething();
);
}
};
答案 1 :(得分:2)
Java中非静态内部类(匿名或命名)的封闭实例可用作 ClassName .this,即
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
doSomethingCleverWith(TextBox.this);
});
}
};
答案 2 :(得分:1)
这对我来说过去很有用。它也适用于客户端js。这是对更多细节的参考 What is the difference between Class.this and this in Java
public class FOO {
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
@Override
public void onFocus(FocusEvent event) {
FOO.this.txt.setHeight("100px");
}
});
}
};
}
答案 3 :(得分:0)
这可能对您有用:
TextBox txt = new TextBox(){
public void onLoad(){
final TextBox ref = this;
this.addFocusHandler(new FocusHandler(){
public void doSomething(){
//some codes
ref.execute();
}
});
}
};
但我更喜欢将内部类迁移到命名类:
public class Test {
public void demo(){
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new DemoFocusHandler(this));
}
};
}
}
外部FocusHandler:
public class DemoFocusHandler extends FocusHandler {
private TextBox textBox;
public DemoFocusHandler(TextBox textBox){
this.textBox = textBox;
}
public void doSomething(){
//some codes
textBox.execute();
}
}
答案 4 :(得分:0)
如果gwt支持反射,你可以采取以下措施:
final TextBox txt = new TextBox() {
public void onLoad() {
final Object finalThis = this;
this.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
try {
Method method= finalThis.getClass().getMethod("getVisibleLength");
method.invoke(finalThis);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
如果没有反思,现在的答案是最好的选择。有两个gwt反射项目gwt reflection和gwt-preprocessor都处于测试阶段,我还没有尝试过。