父类中的Java内联类调用方法 [英] Java inline class calling method in parent class
问题描述
我正在开发一个Swing小应用程序,需要一些帮助.我有一个用于MouseListener的内联类,并且在一个我想在父类中调用方法的方法中,但是,this
是MouseListener的一个实例.
I'm working on a little Swing application and am in need of some assistance. I have an inline class for a MouseListener and inside one of the methods I would like to call a method in the parent class, however, this
is an instance of the MouseListener.
class ParentClass
{
void ParentMethod()
{
//...
swing_obj.addMouseListener(
new MouseListener()
{
public void mouseClicked(MouseEvent e)
{
//Want to call this.methodX("str"), but
//this is the instance of MouseListener
}
public void mouseEntered(MouseEvent e){ }
public void mouseExited(MouseEvent e){ }
public void mousePressed(MouseEvent e){ }
public void mouseReleased(MouseEvent e){ }
}
);
//...
}
void methodX(String x)
{
//...
}
}
任何帮助将不胜感激.
推荐答案
即使this
是匿名类型的实例,您仍然应该能够调用methodX("str")
-只是不要给它加上
Even though this
is an instance of the anonymous type, you should still be able to call methodX("str")
- just don't prefix it with this
.
如果您想露骨,我认为是一些语法可以使您做到这一点-您可以编写
If you want to be explicit, I think there is some syntax which lets you do it - you can write
ParentClass.this.methodX("str");
但就我个人而言,除非您确实需要(例如,消除对MouseListener
中的方法的调用的歧义),否则我不会打扰您.
but personally I wouldn't bother being explicit unless you really have to (e.g. to disambiguate the call from a method in MouseListener
).
这篇关于父类中的Java内联类调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!