gpt4 book ai didi

java - 绑定(bind)不匹配缓解

转载 作者:行者123 更新时间:2023-11-30 11:03:16 26 4
gpt4 key购买 nike

假设我有一个通用接口(interface):

interface SomeInterface<T> {
...
}

和两个实现:

一个特定的(可能针对 SpecificClass 及其后代进行了优化):

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

还有一个 catch all one(也许可以处理所有类型但效率很低):

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>();
}
}

有什么方法可以减轻绑定(bind)不​​匹配错误吗?强制编译器忽略它或类似的某种技巧?

我不必在特定实现上绑定(bind)类型参数,但我宁愿这样做。

最佳答案

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

关于java - 绑定(bind)不匹配缓解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com