Dynamically create an extended anonymous class from a given INSTANCE (override a method from an instance in runtime)

ⅰ亾dé卋堺 提交于 2019-12-11 08:33:55

问题


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?

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.


回答1:


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".

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).

Further reading:

  • Proxy Pattern
  • Delegation Pattern
  • Decorator Pattern

(Yes, I agree it becomes a mess if there are a lot of delegate methods...)



来源:https://stackoverflow.com/questions/10853621/dynamically-create-an-extended-anonymous-class-from-a-given-instance-override-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!