问题
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