I am working with a 3rd party framework and it turns out I need to wrap some of its objects as a delegate to one of my classes.
class Foo { // 3rd party class.
protected void method() {}
}
class FooWrapper extends Foo {
private Foo mDelegate;
public FooWrapper(Foo inDelegate) {
mDelegate = inDelegate;
}
protected void method() {
mDelegate.method(); // error can't access protected method() of mDelegate
}
}
So there is the problem. I need to delegate this method to the internal object but its protected and therefore not accessible.
Any ideas on ways to solve this particular problem? This is for Java 1.3.
Why are you constructing a separate instance of Foo? FooWrapper is already a Foo.
class Foo {
protected void method() {}
}
class FooWrapper extends Foo {
protected void method() {
super.method();
}
}
Edit: if you really have to have separate instance, one way (albeit slightly ugly) is to use reflection:
public class Foo {
protected void method() {
System.out.println("In Foo.method()");
}
}
public class FooWrapper extends Foo {
private Foo foo;
public FooWrapper(Foo foo) {
this.foo = foo;
}
public void method() {
try {
Method m = foo.getClass().getDeclaredMethod("method", null);
m.setAccessible(true);
m.invoke(foo, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Edit2: Based on your comment below, have two sub-classes of Foo, one that simply provides public versions of the protected methods, and one that has overrides all of the important methods. The first will look and act exactly like a Foo, the second can do whatever you need doing:
public class Foo {
protected void method() {
System.out.println("In Foo.method()");
}
}
public class DelegateFoo extends Foo {
public void method() {
super.method();
}
}
public class FooWrapper extends Foo {
private DelegateFoo foo;
public FooWrapper(DelegateFoo foo) {
this.foo = foo;
}
public void method() {
foo.method();
/* extra logic here */
}
}