2015-08-20 137 views
0

这有点奇怪,可能会出现iffy语法,但可以和我一起。我一直在尝试3个月,我相信我需要一种方法来做到这一点:调用静态方法

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()但不能覆盖它。这只是一个例子。实际上,我正在制作一个单元系统,并且我有很多方法取决于getTypeClass(),并且真的是爱不必在每个扩展类(其中有一个不确定的数字)中重写它们,唯一的区别在实现中是类名。

非常感谢!

P.S.这些方法必须是静态的,因为它们被静态调用(并且我宁愿不必创建一个虚拟实例或反射来调用它们)。

+0

不,这是可怕的设计。请提供“单元”用例,我们可以帮助您。这是一个XY问题。 –

+0

*我一直在尝试三个月,我确信我需要一种方法来做到这一点*; **在尝试三个月后**,为什么你如此坚定地相信? –

+0

返回类型void的方法如何返回任何东西?覆盖时添加@Override注释以确保您重写超类中的某些内容。在Java中也无法重写静态方法http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods –

回答

0

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

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

现在,如果你想AB重用init方法,你必须作为参数传递。

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