这是我想用Java反射调用的一段代码:
private void cardSlotMouseClicked(MouseEvent mouseEvent) {
// Some stuff
}
以下是ATM类中调用它的代码:
// cardSlot is a JPanel
this.cardSlot.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent mouseEvent) {
ATM.this.cardSlotMouseClicked(mouseEvent);
}
});
这是我的代码:
Class a = ATM.class;
Method m = a.getDeclaredMethod("cardSlotMouseClicked", MouseEvent.class);
m.setAccessible(true);
Object o = a.newInstance();
m.invoke(o, "?"); // What is the argument?
我尝试过MouseEvent.BUTTON1,但它不起作用。
答案 0 :(得分:0)
您需要一个MouseEvent类型的对象才能传递给此调用方法。您可以使用System Generated MouseEvent(通过鼠标单击创建),也可以使用任何MouseEvent构造函数
创建虚拟鼠标事件在您的情况下,您可以使用这样的反射调用所需的方法:
this.cardSlot.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent mouseEvent) {
Class a = ATM.class;
Method m = a.getDeclaredMethod("cardSlotMouseClicked", MouseEvent.class);
m.setAccessible(true);
Object o = a.newInstance();
m.invoke(o, mouseEvent);
}
});