Dynamically create an extended anonymous class fro

2019-08-01 06:48发布

问题:

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