我正在开发一个 Android 应用程序,我遇到了这种情况:
-GenericOrderDetailFragment,扩展 Fragment 的抽象类。
-此类的三个非抽象“儿子”:LinesFragment、HeaderFragment、NoteFragment。
三个儿子中有很多相同的方法,所以我在抽象类上声明了 then,这就是它存在的原因。
我特别坚持其中一个。现在,我把这个方法放在儿子里面,效果很好:
public class LinesFragment extends GenericOrderDetailFragment {
[...]
public static LinesFragment newInstance(Order o) {
LinesFragment fragment = new LinesFragment();
putSerializable(o, fragment);
return fragment;
}
[...]
}
此方法在所有儿子中都是相同的,除了返回类型:LinesFragment 应该返回 LinesFragment 实例,HeaderFragment 应该返回 HeaderFragment istance ...我想将其作为父类中的必须覆盖,但我不能这样做这是因为:
简单来说
public static GenericOrderDetailFragment newInstance(Order o) {
GenericOrderDetailFragment fragment = new GenericOrderDetailFragment();
putSerializable(o, fragment);
return fragment;
}
方法不起作用,只是因为我无法实例化 GenericOrderDetailFragment (它是抽象的)。我无法实例化 this.getClass() 项,因为没有 this:该方法是静态的!
我无法声明“静态抽象”方法(在java中,静态是“不可覆盖的”,而抽象是“必须覆盖的”,因此它们不能共存),因此我无法强制扩展 GenericOrderDetailFragment 的用户覆盖该方法。
如果我扩展这个通用类,我必须覆盖一些方法,所以我不能声明非抽象的父类。
我可以使用任何解决方法吗?提前致谢!
最佳答案
您可以为此使用反射:
public static <T extends GenericOrderDetailFragment> T newInstance(Class<T> cl, Order o) {
Constructor<T> c = cl.getConstructor();
T fragment = c.newInstance();
...
}
请注意,我遗漏了任何异常
。所以你必须自己进行异常处理。
但基本上这应该是您正在寻找的内容。
关于java - 实现 "static abstract and inheritable"方法的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216812/