使用任意定义的匿名接口方法 [英] Using an arbitrarily defined method of an anonymous interface

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

问题描述

考虑以下代码:

public static void main(String[] args) {
    File file = new File("C:\\someFile.txt") {
        public void doStuff() {
            // Do some stuff
        }   
    };

    file.doStuff(); // "Cannot resolve method"
}

当我们尝试调用新定义的方法时 doStuff(),这是不可能的。原因是文件被声明为 File 类型的对象,而不是我们新的实例,匿名子类。

When we try to call our newly defined method doStuff(), it isn't possible. The reason for this is that file is declared as an object of type File and not as an instance of our new, anonymous child class.

所以,我的问题是,有没有好的方法来实现这种行为?除了显而易见的(只是,正确地宣布这个类)。

So, my question is, is there any 'nice' way to achieve this behaviour? Other than the obvious (which is to just, declare the class properly).

推荐答案

这是不可能的,因为你正试图在超类引用上调用方法子类。并且该方法没有在超类本身中定义。匿名类只是文件的子类。

That's not possible, because you are trying to call the method subclass on super class reference. And that method is not defined in super class itself. The anonymous class is just a subclass of File there.

但是,解决方法是通过反射:

However, a workaround is to go through reflection:

file.getClass().getMethod("doStuff").invoke(file);

getClass() 方法将返回运行时类型 file ,然后你可以使用 Class#getMethod() 方法。

The getClass() method will return the runtime type of file, and then you can get the method for that class using Class#getMethod() method.

嗯,我自己并不是反思的忠实粉丝。如果你要做这些事情,更好的方法当然是通过扩展超类来创建一个类。这将是一个非常痛苦的头脑,使用反射工作,通过简单的修改可以轻松完成。

Well, I'm not a big fan of reflection myself. A better way would of course be to create a class by extending the super class, if you are going to do these kinds of stuff. It would be really a pain in the head, working your way out using reflection, for what can be easily done using a simple modification.

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

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