Java collections provide type via overridable variable -
Java collections provide type via overridable variable -
example code:
public abstract class abstractevent { // extended abstractevent subclasses, used lambda function interface // (all sub-interfaces define 1 method) public interface eventlistener { } // assigned subclasses in static block protected static class<? extends eventlistener> listenerclass; // line not work protected static set<listenerclass> listeners = new hashset<>(); public final boolean addlistener(listenerclass listener) { homecoming listeners.add(listener); } public final boolean removelistener(listenerclass listener) { homecoming listeners.remove(listener); } }
is possible in java, , if so, how? i've made in scala defining type without body in abstract class , defining in subclasses (and works great), i'd create in java aswell.
the point of want avoid duplicating set code in subclasses of abstractevent.
you can't override static variables (see is there way override class variables in java?), , assigning value protected static
variable static block of subclass won't work want either:
class base of operations { protected static string value = "base"; public static string getvalue() { homecoming value; } } class derived extends base of operations { static { value = "derived"; } } class main { public static void main(string[] args) throws exception { // create sure run static initializer derived class class.forname("derived"); system.out.println(derived.getvalue()); system.out.println(base.getvalue()); } }
this print:
derived derived
that not want. same reason current code have listeners
set shared across different subclasses.
if fine having addlistener
, removelistener
non-static, can go this:
// abstractevent.java public abstract class abstractevent<t extends abstractevent.eventlistener> { public interface eventlistener { } protected static map<class<? extends abstractevent>, set<eventlistener>> listeners = new hashmap<>(); public final boolean addlistener(t listener) { set<eventlistener> eventlisteners = listeners.getordefault(getclass(), new hashset<>()); if (!listeners.containskey(getclass())) { listeners.put(getclass(), eventlisteners); } homecoming eventlisteners.add(listener); } public final boolean removelistener(t listener) { set<eventlistener> eventlisteners = listeners.get(getclass()); if (eventlisteners != null) { homecoming eventlisteners.remove(listener); } homecoming false; } } // someevent.java public class someevent extends abstractevent<someevent.someeventlistener> { public interface someeventlistener extends abstractevent.eventlistener { void somemethod(); } }
if want have addlistener
, removelistener
static, generics not going help because can't reference type parameters static methods. in case afraid going have explicitly declare them in each subclass.
java
Comments
Post a Comment