问题描述
我知道抽象类和接口都不能包含一个同时,因为模糊问题,但是有没有解决方法?
我想要一个抽象类或一个要求的接口在所有扩展/实现此类/接口的类中包含静态方法。有没有办法在Java中这样做?如果没有,这可能是我最后一次使用Java ... [/ p>
编辑1:这个问题的背景是我有一堆类,称之为Stick, Ball和Toy现在,在数据库中有一堆条目。我想创建一个名为Fetchable的超类/接口,它需要在它下面的每个类中使用静态方法 getFetchables()
。 Stick,Ball和Toy中的方法必须是静态的原因是因为它们将与数据库通信以检索数据库中每个类的所有条目。
您有几个选择:
- 使用反射来查看方法是否存在然后调用它。
-
为名为@GetAllWidgetsMethod的静态方法创建一个注释。
-
正如其他人所说,尽量不要使用静态方法。
I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?
I want to have either an abstract class or an interface that mandates the inclusion of a static method in all of the classes that extend/implement this class/interface. Is there a way to do this in Java? If not, this may be my final straw with Java...
EDIT 1: The context of this problem is that I have a bunch of classes, call them Stick, Ball, and Toy for now, that have a bunch of entries in a database. I want to create a superclass/interface called Fetchable that requires a static method getFetchables()
in each of the classes below it. The reason the methods in Stick, Ball, and Toy have to be static is because they will be talking to a database to retrieve all of the entries in the database for each class.
EDIT 2: To those who say you cannot do this in any language, that is not true. You can certainly do this in Ruby where class methods are inherited. This is not a case of someone not getting OO, this is a case of missing functionality in the Java language. You can try to argue that you should never need to inherit static (class) methods, but that is utterly wrong and I will ignore any answers that make such points.
You have a couple of options:
- Use reflection to see if the method exists and then call it.
Create an annotation for the static method named something like @GetAllWidgetsMethod.
As others have said, try to not use a static method.
这篇关于Java抽象静态解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!