我有以下界面和类:
public interface SomeInterface {
...
}
public class TypeA implements SomeInterface {
...
}
public class TypeB implements SomeInterface {
...
}
我在其他课程中有以下方法:
public static <T extends SomeInterface> void foo(T a, T b) {
...
}
现在,我如何确保a
和b
来自同一个班级? (TypeA
或TypeB
两者都有,当第一个TypeA
但第二个是TypeB
时
我找到的一个解决方案是在界面中添加一个类型,如下所示:
public interface SomeInterface<T> {
...
}
public class TypeA implements SomeInterface<TypeA> {
...
}
public class TypeB implements SomeInterface<TypeB> {
...
}
并且还修改这样的方法:
public static <T> void foo(SomeInterface<T> a, SomeInterface<T> b) {
...
}
此解决方案有效但对我来说似乎有点奇怪,因为我必须两次写出类名:class A implements SomeInterface<A>
。我想知道是否有比上面更好的解决方案。谢谢。
答案 0 :(得分:0)
在这种情况下,我会使用这些是唯一的两个接口:
public static <T extends SomeInterface> void foo(TypeA a, TypeA b) {
public static <T extends SomeInterface> void foo(TypeB a, TypeB b) {
但是当您的接口数量未知时,您的解决方案也会正常工作。