Meta Generic in Java -
i'm 99% impossible, thought it's worth try: possible create class implements template?
motivation: want create 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() { (t item : m_items) { item.f(); } } }
where f method defined in interface t. of course don't know it's gonna f() when call nor implement it. there meta-meta-magic i'm not aware of makes possible? if not, there other language out there supports this?
you correct, not possible in java: compiler cannot sure t
interface
(as opposed class
), cannot let implement t
.
c++ offers possibility through templates, not implement "generic composite". problem f()
method (or methods in actual class stands). wanted write this:
// not going work! syntax not real. public class genericcomposite<t> implements t { list<t> m_items; void add(t item) { m_items.add(item); } @override <all-methods-of-t>(); }
in order write @override void f()
must know t
has void f()
. need know every single method of t
, which, of course, defeats purpose of hiding t
's identity in first place: genericcomposite<t>
knows there know interface, i.e. methods.
when build composite, having list of sub-elements smaller problem implementing methods let callers treat composite in same way treat leaf objects. these "aggregate" methods custom, making generic structural implementations of composite useless.
Comments
Post a Comment