Given the following hierarchy:
class A
{
}
class B : A
{
public void Foo() { }
}
class C : A
{
public void Foo() { }
}
This is a third-party library and I can't modify it. Is there a way I can write some kind of 'generic templated wrapper' which would forward the Foo() method to the apropriate object passed as constructor argument? I ended up writing the following, which uses no generics and seems rather ugly:
class Wrapper
{
A a;
public Wrapper(A a)
{
this.a = a;
}
public void Foo()
{
if (a is B) { (a as B).Foo(); }
if (a is C) { (a as C).Foo(); }
}
}
I'd love some template constraint like Wrapper<T> where T : B or C
.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
Overview. As the name suggests, wrapper classes are objects encapsulating primitive Java types. Each Java primitive has a corresponding wrapper: boolean, byte, short, char, int, long, float, double.
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.
If A
does not have Foo
, you need to either use dynamic
(see Jon Skeet's answer) or use a little trick with lambdas and overloading:
class Wrapper {
private Action foo;
public Wrapper(B b) {
foo = () => b.Foo();
}
public Wrapper(C c) {
foo = () => c.Foo();
}
public void Foo() {
foo();
}
}
Now you can do this:
var wb = new Wrapper(new B());
wb.Foo(); // Call B's Foo()
var wc = new Wrapper(new C());
wc.Foo(); // Call C's Foo()
This shifts the decision on what method to call from the moment the Foo
is called to the moment the Wrapper
is created, potentially saving you some CPU cycles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With