Java - An interface that has static field pointing to class name of its sub class?

别说谁变了你拦得住时间么 提交于 2020-01-15 11:08:49

问题


I want an interface, which its sub class can inherit a static field, that field points to the name of the sub class.

How can I do that?

For example in my mind (the code is unusable):

public interface ILogger<A> {

    public static String LogTag = A.class.getName();
}

public class Sub implements ILogger<Sub> {

    public Sub() {
        Log.debug(LogTag, ...);
    }
}

回答1:


In Java, unlike C++, this is not possible due to the way that generics are implemented. In Java, there is only one class for each generic type, not multiple copies for each time a different type argument is used (this is called erasure). As a result, you can't have a single variable that points to the class object of its subtype, because there can be many subtypes but there is always exactly one copy of the static field. This contrasts with C++, where each time the ILogger template is instantiated you would get your own copy of that static field.

One possible approximation would be to have a Map as a static field that associates class objects with strings, as in

public static final Map<Class, String> classMap = new HashMap<Class, String>();

You would then have to have each subtype explicitly add itself to this map, perhaps with a static initializer:

public class Sub implements ILogger<Sub> {

    static {
        ILogger.classMap.put(Sub.class, /* ... value ... */);
    }

    public Sub() {
        Log.debug(LogTag, ...);
    }
}

Hope this helps!



来源:https://stackoverflow.com/questions/9577538/java-an-interface-that-has-static-field-pointing-to-class-name-of-its-sub-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!