1

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, ...);
    }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

1 Answers1

3

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Thank you for concept of `erasure`, I just know it for now. But I wish a more concise solution. As instead of your code, I can type `public static final String LogTag = Sub.class.getName()`. But, thanks again :-) –  Mar 06 '12 at 03:46
  • 1
    Unfortunately, there isn't a more concise solution in Java. – Stephen C Mar 06 '12 at 03:53
  • Downvoter- Can you please explain what's wrong with this answer or how to improve it? – templatetypedef Mar 06 '12 at 04:08
  • @templatetypedef No worries, your answer really helps me. If you have experiences with Android, would you please help me on this one: http://stackoverflow.com/questions/2561161/how-to-avoid-eclipse-leaks-on-xserver-when-editing-android-xml-files –  Mar 06 '12 at 04:15
  • @StephenC: Yes there is. But in another viewpoint. I can write my own logger, which takes `Sub.class` as a logtag, instead of a string. –  Mar 06 '12 at 04:26