Re: How to extends a class at runtime?
alex wrote:
I don't know whether the subject is proper, sorry for any confusion.
Now, I have a class A, which is not controlled myself and I can only
get an instance of it at runtime. However, I want to do some adapter
work to it, such as altering its interface.
My solution is using the instance of A as a constructor parameter of a
new adapter class B, for example:
class B {
private A a;
public B(A aa) {
a = aa;
}
/* adapter stuff here ... */
}
Of course, it works. But I am now wondering whether there is a
solution using inheritance instead of composition? Is there any
pattern or trick?
Most of the time you're going to be better off composing a wrapper class than
extending the target class. This is true even when you control the source.
As an example, consider Collections.unmodifiableCollection( Collection <?
extends T> c). It works by extending the Collection interface, but by
wrapping the target object rather than trying to dynamically extend the target
object's actual class. This has a host of advantages - the resulting
collection need not try to handle, say, List-specific methods even though
object c might be a List, and of course, it's a lot faster, shorter and safer
than trying to dynamically re-extend the class of 'c'.
So even if you are extending, you can also compose. You can extend, in your
example, class or interface A with B, but still compose around an instance of
A internally. That way you aren't dynamically creating classes but have one
created the usual way, with source code and all that.
--
Lew