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.这些方法做必须是静态的,因为它们被静态调用(并且我宁愿不必创建一个虚拟实例或反射来调用它们)。
不,这是可怕的设计。请提供“单元”用例,我们可以帮助您。这是一个XY问题。 –
*我一直在尝试三个月,我确信我需要一种方法来做到这一点*; **在尝试三个月后**,为什么你如此坚定地相信? –
返回类型void的方法如何返回任何东西?覆盖时添加@Override注释以确保您重写超类中的某些内容。在Java中也无法重写静态方法http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods –