I'm 99% certain this is impossible, but I thought it's worth a try: Is it possible to create a class that implements a template?
Motivation: I want to create a generic composite class.
Example:
public class GenericComposite<T> implements T {
List<T> m_items;
void add(T item) {
m_items.add(item);
}
@Override
void f() {
for (T item : m_items) {
item.f();
}
}
}
Where f is the method defined in the interface T. Of course we don't know it's gonna be f() when we call it nor where we implement it. Is there some meta-meta-magic I'm not aware of that makes this possible? If not, is there some other language out there that supports this?
You are correct, this is not possible in Java: the compiler cannot even be sure that
T
is aninterface
(as opposed to aclass
), so it cannot let you implementT
.C++ offers this possibility through templates, but even this would not help you implement a "generic composite". The problem is the
f()
method (or the methods in the actual class for which it stands). What you wanted to write is this:In order to write
@Override void f()
you must know thatT
hasvoid f()
. You need to know this about every single method ofT
, which, of course, defeats the purpose of hidingT
's identity in the first place: yourGenericComposite<T>
knows everything there is to know about the interface, i.e. all its methods.When you build a composite, having a list of sub-elements is a much smaller problem than implementing methods that let the callers treat the composite in the same way as they treat leaf objects. All these "aggregate" methods are always custom, making generic structural implementations of composite nearly useless.