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, ...);
}
}
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
ILoggertemplate is instantiated you would get your own copy of that static field.One possible approximation would be to have a
Mapas a static field that associates class objects with strings, as inYou would then have to have each subtype explicitly add itself to this map, perhaps with a static initializer:
Hope this helps!