你让自己陷入了什么巫术:)?从问题和评论中,我假设您确定您拥有扩展抽象类SomeClass
并实现接口的对象SomeOtherClass
。如果是这种情况,我建议在层次结构中使用一个共享这些属性的中间抽象类。
public abstract class Foo<K> extends SomeClass implements SomeOtherClass<K> {
...
}
这样,您可以将静态方法签名简化为:
public <K,V extends Foo<K>> void doSomethingWithSomeMap (Map<K,V> map, V data);
如果您不想更改当前的对象层次结构,您可以使用适配器模式的另一个间接级别来欺骗编译器。
“计算机科学中的所有问题都可以通过另一个层次的间接性来解决。” ——大卫·惠勒
public abstract class SomeClass {
public abstract void method1();
}
public interface SomeOtherClass<K> {
void method2(K value);
}
public class MyClass extends SomeClass implements SomeOtherClass<Integer> {
@Override
public void method1() {
System.out.println("MyClass.method1");
}
@Override
public void method2(Integer value) {
System.out.println("MyClass.method2(" + value + ")");
}
}
public class Indirection<K> extends SomeClass implements SomeOtherClass<K> {
private final Object objectValue;
public Indirection(final Object value) {
this.objectValue = value;
}
@Override
public void method1() {
((SomeClass) objectValue).method1();
}
@Override
public void method2(K value) {
@SuppressWarnings("unchecked")
SomeOtherClass<K> delegate = ((SomeOtherClass<K>) objectValue);
delegate.method2(value);
}
}
public static void main(String[] args) {
Map someMap = new HashMap<Integer, MyClass>();
SomeClass someData = new MyClass();
Indirection a = new Indirection(someData);
doSomethingWithSomeMap(someMap, a, 12);
}
public static <K,V extends SomeClass & SomeOtherClass<K>>
void doSomethingWithSomeMap (Map<K,V> map, V data, K value) {
data.method1();
data.method2(value);
}
这将打印:
MyClass.method1
MyClass.method2(12)