我遇到了 Java 和 Apache Wicket 1.5 的问题,其中两个匿名类的封闭 Java 对象的身份发生了变化!
在一个 Wicket 模式窗口中,我想创建第二个模式窗口(用于获取文本字符串提示),然后使用 AJAX 刷新模型(字符串-整数对列表)更新原始模式窗口。
基本上我在同一个方法中创建了两个匿名类,但是封闭实例的“this”指针在一个匿名类和另一个匿名类之间是不同的。
这对我来说似乎不是正常的预期 JVM 行为,但我也无法在 Java 规范中找到任何关于它如何工作的细节。
public class DropDownChoiceModal extends WebPage {
public String newTermResponse;
private void addAddTermModal() {
addTermModal = new ModalWindow("add_term_modal");
addTermModal.setPageCreator(new ModalWindow.PageCreator() {
public Page createPage() {
PropertyModel pm = new PropertyModel<String>(DropDownChoiceModal.this, "newTermResponse");
System.out.println ("propModel: " + System.identityHashCode(DropDownChoiceModal.this));
return new TextInputModal(addTermModal, "What is the new term you wish to add?", pm);
}
});
addTermModal.setWindowClosedCallback(new WindowClosedCallback() {
public void onClose(AjaxRequestTarget target) {
System.out.println ("propModel: " + System.identityHashCode(DropDownChoiceModal.this));
System.out.println ("newTermResponse: " + DropDownChoiceModal.this.newTermResponse);
// If the value is set then use it
if (newTermAvailable()) {
// Add the new term to the model
model.add(new StringIntegerPair (newTermResponse, 0));
System.out.println ("Update view: " + model.size());
// Update the view
target.add(wmc);
}
System.out.println ("No new term");
}
private boolean newTermAvailable() {
return (newTermResponse != null) && !newTermResponse.isEmpty();
}
});
add(addTermModal);
}
对于 TextInputModal 类:
public class TextInputModal extends WebPage {
public TextInputModal(final ModalWindow modal, String requestString, final IModel<?> model) {
Form<String> form = new Form<String>("form") {
public void onSubmit() {
System.out.println ("Submitted: " + System.identityHashCode(((PropertyModel)model).getTarget()) + "; " + model.getObject());
}
};
// Add the buttons
form.add(new AjaxButton("ok") {
public void onAfterSubmit(AjaxRequestTarget target, Form<?> form) {
System.out.println ("Submitted 2: " + System.identityHashCode(((PropertyModel)model).getTarget()) + "; " + model.getObject());
modal.close(target);
}
});
// Add the form
add(form);
}
}
我得到的输出:
propModel: 698650686
Submitted: 698650686; fdsfds
Submitted 2: 698650686; fdsfds
propModel: 1447892364
newTermResponse: null
No new term
当在同一方法中创建匿名类 1 ( new ModalWindow.PageCreator() {} ) 和匿名类 2 ( new WindowClosedCallback() {} ) 时,为什么封闭实例 (DropDownChoiceModal.this) 的身份发生了变化的任何想法( addAddTermModal() )?
提前致谢...
奈杰尔