如何将接口中的Java泛型类型参数限制为某些类 [英] How to restrict Java generics type parameter in interface to certain classes
问题描述
我正在创建一个类型化的接口定义,我想将type参数的可能值限制为一组类.这些类已经存在,不受我的控制.而且,它们之间没有通过类层次结构相互关联.
I am creating a typed interface defintion and I want to restrict the possible values for the type parameter to a set of classes. These classes are existing already and are not under my control. Also, they are not related to each other through the class hierarchy.
例如,我有三个类A,B,C.我的界面是 IMyFancyInterface< T>
.如何限制此接口的实现者,并确保T仅是A,B或C?非常感谢.
So, for example, I have three classes A, B, C. My interface is IMyFancyInterface<T>
.
How can I restrict implementors of this interface and make sure that T is either A, B, or C only?
Thanks a lot.
干杯
马丁
推荐答案
如果 A
, B
和 C
具有共同的超类型(假设它称为 Super
),那么您可以这样做:
If A
, B
and C
have a common super-type (let's say it's called Super
), then you could do:
public interface IMyFancyInterface<T extends Super> { .. }
这样,您应该始终使用类型参数来实现此接口,该类型参数是 Super
的子类型,即 A
, B
或 C
.
This way you should always implement this interface with a type-parameter that is a sub-type of Super
, i.e. A
, B
or C
.
但是,如果 A
, B
和 C
没有通用的超级类型,则可以创建标记接口(一个没有抽象方法的接口)并使其实现.例如:
If, however, A
, B
and C
don't have a common super-type, you could create a marker interface (an interface with no abstract methods) and make them implement it. For example:
public interface Marker { }
public class A implements Marker { }
public class B implements Marker { }
public class C implements Marker { }
这样,您就可以遵循我最初建议的方法:
This way you'd be able to follow the approach I initially suggested:
public interface IMyFancyInterface<T extends Marker> { .. }
这篇关于如何将接口中的Java泛型类型参数限制为某些类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!