Java - 一个静态字段指向其子类的类名的接口? [英] Java - An interface that has static field pointing to class name of its sub class?

查看:69
本文介绍了Java - 一个静态字段指向其子类的类名的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个接口,它的子类可以继承一个静态字段,该字段指向子类的名称。

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

我该怎么做?

例如在我看来(代码无法使用):

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, ...);
    }
}


推荐答案

Java与C ++不同,由于泛型的实现方式,这是不可能的。在Java中,每个泛型类型只有一个类,而不是每次使用不同类型参数时的多个副本(这称为 擦除 )。因此,您不能有一个指向其子类型的类对象的单个变量,因为可能有许多子类型,但始终只有一个静态字段副本。这与C ++形成了鲜明对比,每当 ILogger 模板被实例化时,您将获得您自己的该静态字段的副本。

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.

一个可能的近似值是将 Map 作为一个将类对象与字符串相关联的静态字段,如

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, ...);
    }
}

希望这有助于您!

这篇关于Java - 一个静态字段指向其子类的类名的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆