根据给定的INSTANCE动态创建扩展的匿名类(在运行时重写实例中的方法) [英] Dynamically create an extended anonymous class from a given INSTANCE (override a method from an instance in runtime)

查看:73
本文介绍了根据给定的INSTANCE动态创建扩展的匿名类(在运行时重写实例中的方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法动态地创建给定另一个扩展匿名实例? 会是这样,我认为那太好了.

Is there any way to create dynamically an extended anonymous instance given another one? Would be something like this, and I think it would be great.

File myFile = new File("notes.txt");

new FileWrapper extends myFile(){ //instance!!!
   @Override public boolean equals(File in){ return false;}
};

这就像复制对象实例并在特定方法内重新编写逻辑 如果不是,最好的方法是什么?

This is like copying the object instance and rewritting the logic inside a particular method If not whats the best way of achieving it?

注意:我知道如果myFile是类的名称而不是and实例,则该示例有效,但是我应该做一些事情来保存实例vars和内部信息.

Note: I know that the example is valid if myFile is a class´s name and not and instance, but then I should do something to hold the instances vars and inner info.

推荐答案

不,Java中没有这样的功能.您必须依靠将对象转发到原始实例的代理对象,但要覆盖"的调用除外.

No, there's no such feature in Java. You'll have to rely on proxy objects that forwards calls to the original instance except for the calls it wants to "override".

请注意,如果希望代理对象与原始对象具有相同的 type ,则需要使用接口,因为如果代理对象将扩展原始类型,则最终会两个实例(如果是包装对象可以工作,则不必要).

Note that if you want the proxy object to have the same type as the original object, you need to use interfaces, since if the proxy object would extend the original type, you would end up with two instances (which would be unnecessary if it is the wrapped object that does the work).

进一步阅读:

  • Proxy Pattern
  • Delegation Pattern
  • Decorator Pattern

(是的,我同意,如果有很多委托方法,那将变得一团糟...)

这篇关于根据给定的INSTANCE动态创建扩展的匿名类(在运行时重写实例中的方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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