2015-05-27 44 views
2

说我有一个通用的接口:绑定不匹配缓解

interface SomeInterface<T> { 
... 
} 

和两种实现方式:

特定的一个(也许是SpecificClass优化及其后代):

class SpecificImplementation<T extends SpecificClass> implements SomeInterface<T> { 
... 
} 

和另一赶上所有的(也许可以处理所有类型,但效率非常低):

class CatchAllImplementation<T> implements SomeInterface<T> { 
.... 
} 

而且我希望有类似以下的一般方法:

public <T> SomeInterface<T> getImplementation(Class<T> clazz) { 
    if(SpecificClass.class.isAssignableFrom(clazz)) 
    { 
    // do some specific stuff 

    ... 

    // get specific optimised implementation for SpecificClass and descendents 
    return new SpecificImplementation<T>(); // bound mismatch error here 
    } 
    else 
    { 
    // do other stuff 

    ... 

    // get inefficient catch all implementation in other cases 
    return new CatchAllImplementation<T>(); 
    } 
} 

有减轻对绑定的失配误差的方法吗?某种强制编译器忽略它或类似的技巧?

我不必在具体实现上绑定类型参数,但我宁愿这样做。

+0

你不能使用类似'类SpecificImplementation实现SomeInterface '或'类SpecificImplementation 实现SomeInterface '? – JimmyB

回答

1
public class Main {  
    public <T> SomeInterface<T> getImplementation(Class<T> clazz) { 
     if(SpecificClass.class.isAssignableFrom(clazz)) 
     { 
      // do some specific stuff 

      // unchecked cast here... 
      return (SomeInterface<T>) getSpecificImplementation((Class<SpecificClass>) clazz); 
     } 
     else 
     { 
      // do other stuff 
      return new CatchAllImplementation<T>(); 
     } 
    } 

    private <T extends SpecificClass> SomeInterface<T> getSpecificImplementation(Class<T> clazz) { 
     return new SpecificImplementation<T>(); 
    } 

    public static void main(String[] args) { 
     Main m = new Main(); 
     SomeInterface<SpecificClass> implementation = m.getImplementation(SpecificClass.class); 

     System.out.println("Result: " + implementation.getClass()); 
     SomeInterface<Object> catchAll = m.getImplementation(Object.class); 

     System.out.println("Result: " + catchAll.getClass()); 

     SomeInterface<SpecificClassChild> implementationForChild = m.getImplementation(SpecificClassChild.class); 

     System.out.println("Result: " + implementationForChild.getClass()); 
    } 
} 

它打印:

Result: class timo.generics.SpecificImplementation 
Result: class timo.generics.CatchAllImplementation 
Result: class timo.generics.SpecificImplementation 
+0

这是否适用于扩展SpecificClass的类型参数类? – PaddyD

+0

不知道我是否明白你的意思,但我试过这个:做了一个'SpecificImplementationChild 扩展SpecificImplementation '。在私有'getSpecificImplementation'方法中返回此Child的新实例。这个打印出来的结果是:class timo.generics.SpecificImplementationChild'作为第一行。 – Timo

+0

对不起,请仔细阅读... – Timo

0

这是因为SpecificImplementation需要一个扩展了SpecificClass的T。

你可以逃脱使用SpecificImplementation无类型:

return new SpecificImplementation(); 

一个更好的解决办法是利用继承的,而不是使用if语句。

+0

我不确定继承如何帮助?我需要使用反射来确定基于类型参数的类使用哪种通用实现。 – PaddyD

+0

我不知道你的用例,但是检查对象实例的一系列if语句通常是不好的做法。 – Robert