Java抽象静态解决方法 [英] Java abstract static Workaround

查看:187
本文介绍了Java抽象静态解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道抽象类和接口都不能包含一个同时抽象和静态,因为模糊问题,但是有没有解决方法?



我想要一个抽象类或一个要求的接口在所有扩展/实现此类/接口的类中包含静态方法。有没有办法在Java中这样做?如果没有,这可能是我最后一次使用Java ... [/ p>

编辑1:这个问题的背景是我有一堆类,称之为Stick, Ball和Toy现在,在数据库中有一堆条目。我想创建一个名为Fetchable的超类/接口,它需要在它下面的每个类中使用静态方法 getFetchables()。 Stick,Ball和Toy中的方法必须是静态的原因是因为它们将与数据库通信以检索数据库中每个类的所有条目。



<编辑2:对于那些说你不能用任何语言做到这一点的人,那是不正确的。你当然可以在Ruby中继承类方法。这不是某人没有获得OO的情况,这是Java语言中缺少功能的情况。你可以试着争辩说你永远不需要继承静态(类)方法,但这是完全错误的,我会忽略任何能产生这些要点的答案。

解决方案

您有几个选择:


  1. 使用反射来查看方法是否存在然后调用它。

  2. 为名为@GetAllWidgetsMethod的静态方法创建一个注释。


  3. 正如其他人所说,尽量不要使用静态方法。



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:

  1. Use reflection to see if the method exists and then call it.
  2. Create an annotation for the static method named something like @GetAllWidgetsMethod.

  3. As others have said, try to not use a static method.

这篇关于Java抽象静态解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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