【问题标题】:Calling the Static Method of调用静态方法
【发布时间】:2015-11-13 12:11:27
【问题描述】:

这有点奇怪,可能语法有问题,但请支持我。我已经尝试了三个月,我确信我需要一种方法来做到这一点:

public abstract class Sup{
    ...
    //This is implemented here because I cannot create an abstract static
    //only implemented by the children but called statically by methods in
    //the parent (more info later on in the post):
    protected static Class<? extends Sup> getTypeClass(){ return Sup.class };
    public static void init(){
        ...
        alreadyDeclaredHashMap.put(getTypeClass(), hashMapOfOtherStuff);
    }
}

public class A extends Sup{
    static{
        init();
    }
    protected static void getTypeClass(){ return A.class };
}
public class B extends Sup{
    static{
        init();
    }
    protected static void getTypeClass(){ return B.class };
}
... and so on.

所以如果我要打印出alreadyDeclaredHashMap,它看起来像:

    class A -> hashMapOfOtherStuff
    class B -> hashMapOfOtherStuff
    class C -> hashMapOfOtherStuff
    ...

但它会打印:

    class Sup -> hashMapOfOtherStuff
    class Sup -> hashMapOfOtherStuff
    class Sup -> hashMapOfOtherStuff
    ...

因为扩展类隐藏了getTypeClass(),但不能覆盖它。这只是一个例子。实际上,我正在制作一个 Units 系统,并且我有很多方法取决于 getTypeClass(),并且真的希望不必在每个扩展类中重写它们(其中有一个不定的数字),唯一的区别是实现的类名。

非常感谢!

附:这些方法确实必须是静态的,因为它们是静态调用的(我宁愿不必创建虚拟实例或反射来调用它们)。

【问题讨论】:

  • 不,这是糟糕的设计。请提供“单位”用例,以便我们为您提供帮助。这是一个 XY 问题。
  • 我已经尝试了三个月,我确信我需要一种方法来做到这一点; 经过三个月的努力,你为什么如此坚定地相信?
  • 返回类型为 void 的方法如何返回任何东西?覆盖时添加 @Override 注释以确保您正在覆盖超类中的某些内容。 Java中也不能覆盖静态方法stackoverflow.com/questions/2223386/…
  • 依赖 getTypeClass() 是什么意思?他们有开关盒?如果是,那么不必重写它们。如果不是,请分享您的用例。通过策略模式或泛型可能会更好。除非您提供问题而不是解决方案,否则不确定什么是确切的。

标签: java inheritance methods static call


【解决方案1】:

没有办法让它工作。类sup 中的静态代码不知道类A 和类B,即使从其中之一调用init 方法也是如此。

静态方法不是“virtual”,因此从Sup 中的静态代码调用getTypeClass() 将调用该实现,而不是任何子类实现。

现在,如果您想要重用来自ABinit 方法,则必须作为参数传递。

public abstract class Sup{
    ...
    public static void init(Class<? extends Sup> typeClass) {
        ...
        alreadyDeclaredHashMap.put(typeClass, hashMapOfOtherStuff);
    }
}

public class A extends Sup {
    static {
        init(A.class);
    }
}
public class B extends Sup {
    static {
        init(B.class);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多