[英]Can I have a class field that is the Class<?> of a type that must extend another class and an interface?
很抱歉,我似乎无法用更好的句子来问这个问题。 我将尝试澄清:
我的类(当前是一个enum
,但是如果可以解决此问题,则将其移植到class
中不是问题)具有一个Class字段,该字段指示它将在运行时动态实例化的类型。
此类型必须扩展Fragment
类(Android)并实现MyInterface
。
<F extends Fragment & MyInterface>
如何在代码中定义?
当前有效的是一个不完整的解决方案,该解决方案可以接受任何Fragment,无论它是否实现MyInterface
:
public enum Something {
Value1 (OneFragmentInterfaceImplementor.class),
Value2 (AnotherFragmentInterfaceImplementor.class);
public final Class<? extends Fragment> fragment;
private Something (final Class<? extends Fragment> fragmentClass) {
fragment = fragmentClass;
}
}
我真正想要的是,该类不仅扩展Fragment
,而且实现MyInterface
。
我想要以下正确的形式:
public <F extends Fragment & MyInterface> enum Something {
Value1 (OneFragmentInterfaceImplementor.class),
Value2 (AnotherFragmentInterfaceImplementor.class);
public final Class<F> fragment;
private Something (final Class<F> fragmentClass) {
fragment = fragmentClass;
}
}
我在这里问不可能吗?
更新一个很棒的建议是创建一个实现该接口的抽象Fragment。 不幸的是,这在我的特定用例中不起作用,因为其中一些片段扩展了其他已经实现的片段。
为了在不能接受通用类型参数的enum
使用,请创建一个扩展Fragment
并实现MyInterface
的抽象类。 使您的实现扩展此类。 并与Class
一起使用。
private final Class<AbstractClassThatExtendsFragmentAndImplementsMyInterface> fragment = ...;
你说过
不幸的是,这在我的特定用例中不起作用,因为其中一些片段扩展了其他已经实现的片段。
另一种(半)解决方案是使声明的字段只有一个界限,但是构造函数中的参数有两个界限。 我说一半的解决方案,因为访问Class
字段时将无法获得类型界限。
public enum Something {
Value1(OneFragmentInterfaceImplementor.class), Value2(
AnotherFragmentInterfaceImplementor.class);
public final Class<? extends Fragment> fragment;
private <T extends Fragment & Interface> Something(final Class<T> fragmentClass) {
fragment = fragmentClass;
}
}
如果可以使用class
,则可以声明
public class Example<T extends Fragment & MyInterface> {
private final Class<T> fragment = ...;
// ...
}
您不能在'diamond'(<>)运算符中传递'implements'子句,因为它仅接受类类型。 要解决所需的需求,可以创建一个类(如果不想让用户创建此类型的对象,则可以创建一个抽象类)以扩展Fragment并实现接口,然后在Diamond运算符中传递该接口。 简单的说:
class Holder extends Fragment implements MyInterface // Mark as abstract if user should not instantiate
public final Class<? extends Holder> fragment;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.