从匿名类调用新定义的方法 [英] Calling newly defined method from anonymous class

查看:127
本文介绍了从匿名类调用新定义的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实例化了一个匿名类的对象,我在其中添加了一个新方法。

I instantiated an object of an anonymous class to which I added a new method.

Date date = new Date() {
    public void someMethod() {}
}

我想知道是否有可能从外面以某种方式调用此方法类似于:

I am wondering if it is possible to call this method from outside somehow similar to:

date.someMethod();


推荐答案

好问题。答案是否定的。您无法直接调用 date.someMethod();

让我们先了解这是什么。

Good question. Answer is No. You cannot directly call date.someMethod();
Let's understand first what is this.

Date date = new Date()  { ... }; 

上面是匿名(没有名字)子类,它正在扩展Date类。

Above is anonymous(have no name) sub-class which is extending Date class.

当你看到代码时,

When you see the code like,

    Runnable r = new Runnable() {

        public void run() {

        }

    };

这意味着你已经定义了匿名(没有名字)类正在实现(没有扩展)Runnable接口。

It means you have defined anonymous(have no name) class which is implementing(not extending) Runnable interface.

所以当你打电话给 date.someMethod()时,将不会能够调用,因为 someMethod 超类中定义为 在上述情况下超类是日期类。它遵循简单的重写规则。

So when you call date.someMethod() it won't be able to call because someMethod is not defined in superclass. In above case superclass is Date class. It follows simple overriding rules.

但是如果你想调用 someMethod 然后关注是一步。


Fisrt way>
使用引用变量' date '

date.getClass()。getMethod(someMethod)。invoke(date);

But still if you want to call someMethod then following is the step.

Fisrt way>
With reference variable 'date'
date.getClass().getMethod("someMethod").invoke(date);

第二种方式>

使用新创建的Date类对象的匿名子类。

Second way>
With newly created anonymous sub-class of Date class's object.

new Date() 
{
    public void someMethod() {
          System.out.println("Hello");
    }
}.someMethod();   //this should be without reference 'date'

这篇关于从匿名类调用新定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆