问题
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>
.
How can I restrict implementors of this interface and make sure that T is either A, B, or C only?
Thanks a lot.
Cheers,
Martin
回答1:
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> { .. }
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
.
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> { .. }
回答2:
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:
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 ...
}
}
回答3:
I have now created a work-around by creating abstract classes for the three classes A, B, C which implement the interface. 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.
来源:https://stackoverflow.com/questions/39287025/how-to-restrict-java-generics-type-parameter-in-interface-to-certain-classes