decorator quiz – subclassing by reflection

(See background below)
I agree with you that reflection, using dynamic proxy, can automatically redirect or wrap all 200 public methods, so won’t look super long and needs no code change when adds methods. This does require that those 200 (public) methods are specified in an interface. This is usually not hard – just ask the author to create the interface and make implement it. Not possible if comes from a 3rd-party library.

More importantly, reflective subclass falls short on several fronts.
* Biggest shortfall — If base class has a public method printMe() that calls this.toString(), then a regular subclass can override toString() and it will be invoked by printMe(). Doesn’t work in reflective subclass. “this” is a kind of address in JVM, shared by both acct1 and checking1 in a regular subclass scenario. In the reflective case, checking1 has a different JVM address than acct1, so this.toString() can’t be intercepted by our proxy but goes through regular dynamic binding via virtual table.
* If Account has protected methods and fields, then a regular subclass can easily use them. Not so easy in reflective subclass.
* If Account has a final public field pf1, then in main(), we can say System.out.print(checking1.pf1) only if CheckingAccount is a regular subclass.
* We can cast checking1 from Account to CheckingAccount only for regular subclass

From: Tan, Bi
See if you have any good solution —

public static void main(...){
Account acct1 = getAccountFromDB(123);
CheckingAccount checking1 = new CheckingAccount (....); // Somehow create a CheckingAccount instance whose parent object is acct1.
... } class already has 200 public methods. should inherit all and override toString(). How?


Fill in your details below or click an icon to log in: 徽标

您正在使用您的 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s