Re: How to extends a class at runtime?
Lew <lew@lewscanon.com> wrote in
news:HL6dnYyLtcrw993anZ2dnUVZ_umlnZ2d@comcast.com:
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?
My apologies for replying over Lew's response, I missed the original post
which is now gone from my server.
As Lew pointed out, composition may be a better answer than inheritance.
However, if you want to try a form of runtime inheritance, you could try
using dynamic proxies. See the javadocs for java.lang.reflect.Proxy
If you need help with this, you can get explanations and examples in
"Java Reflection in Action" (In Action series) by Ira R. Forman and Nate
Forman.
java.lang.reflect.Proxy requires that your class A have a defined
Interface.
"Java Reflection in Action" hints at how to get around this limitation.
You may have to see the book's web site (I did) for a better hint at how to
get around this limitation.
Caveat 1: I have no connection to this book except as a purchaser/reader.
Caveat 2: After studying this book, you may see reflection as the answer
to all problems. It isn't. However, the book can be helpful for those
cases where reflection is needed.