如何调用我在匿名 class 中定义的额外方法?

How can i call extra method that i define in anonymous class?

我的示例显示我尝试向 Runnable 匿名 class 添加一些额外的方法,通常我如何调用我创建的额外方法。

Runnable myRunnable = new Runnable()
{
    public void run()
    {
        System.out.println("Running");
    }
    // any  extra method to explain the question 
    public void a()
    {
        System.out.println("A");
    }

};
myRunnable.run();
myRunnable.a(); // is this right??

你怎么会做这种事?您的 myRunnable 对象属于 java.lang.Runnable 类型。除了那里已经存在的方法之外,它没有任何其他方法。 Java 在运行时无法知道分配给 myRunnable 的实际对象实际上是您自己的实现。

但是,您可以这样做:

class MyRunnable implements Runnable {
    @Override
    public void run() { }
    public void myMethod() { }
}

然后

MyRunnable mr = new MyRunnable();
mr.myMethod();