简体   繁体   English

如何将接口中的Java泛型类型参数限制为某些类

[英]How to restrict Java generics type parameter in interface to certain classes

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. 而且,它们之间没有通过类层次结构相互关联。

So, for example, I have three classes A, B, C. My interface is IMyFancyInterface<T> . 因此,例如,我有三个类A,B,C。我的接口是IMyFancyInterface<T> How can I restrict implementors of this interface and make sure that T is either A, B, or C only? 如何限制此接口的实现者,并确保T仅是A,B或C? Thanks a lot. 非常感谢。

Cheers, 干杯,

Martin 马丁

If A , B and C have a common super-type (let's say it's called Super ), then you could do: 如果ABC具有通用的超类型(假设它称为Super ),则可以执行以下操作:

public interface IMyFancyInterface<T extends Super> { .. }

This way you should always implement this interface with a type-parameter that is a sub-type of Super , ie A , B or C . 这样,您应该始终使用类型参数来实现此接口,该类型参数是Super的子类型,即ABC

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. 但是,如果ABC没有通用的超类型,则可以创建一个标记接口(一个没有抽象方法的接口)并使它们实现它。 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> { .. }

You can't. 你不能 If it's possible, consider the following code: 如果可能,请考虑以下代码:

class MyClass implements IMyFancyInterface<T>
{
    <T extends A | B | C> void DoSomething(T o)
    {
        // what should the parameter o behave like?
        // o.???
    }
}

You can use non-generic methods if there is only a few A/B/C implementations: 如果只有几个A / B / C实现,则可以使用非泛型方法:

interface MyFancyInterface
{
    void DoA(A a);
    void DoB(B b);
    void DoC(C c);
}

or cast in one method: 或采用一种方法进行转换:

interface MyFancyInterface
{
    void Do(Object o);
}

class MyClass implements MyFancyInterface
{
    public void Do(Object o)
    {
        if (o instanceof A)
        {
            //do something with A
        }
        else if ...
    }
}

I have now created a work-around by creating abstract classes for the three classes A, B, C which implement the interface. 我现在通过为实现该接口的三个类A,B,C创建抽象类来创建解决方法。 So, instead of implementing the interface, further visitor classes need to be derived from one of these abstract classes. 因此,除了实现接口之外,还需要从这些抽象类之一派生其他访问者类。 Seems a bit verbose, but apparently there is no other way. 似乎有点冗长,但显然没有其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM