java - 如何满足参数类型Class<?在java中扩展someInterface>

标签 java generics

考虑以下代码

@Test
public void testFunction() {
    // This cause error
    callDoSomething(new myInterfaceImpl());
}

public interface myInterface {
    int doSomething();
}

public class myInterfaceImpl implements myInterface {
    public int doSomething() {
        return 1;
    }
}

public void callDoSomething(Class<? extends myInterface> myVar) {
    System.out.println(myVar.doSomething());
}

在这一行callDoSomething(new myInterfaceImpl());我收到以下错误。

Error:(32, 25) java: incompatible types: com.myProject.myTest.myInterfaceImpl 
cannot be converted to java.lang.Class<? extends com.myProject.myTest.myInterface>

如何满足参数类型?如果只提供一个接口(interface)给我就好了。

我想绑定(bind)具有接口(interface)的类,但似乎这对我来说不可用

Class<? implements myInterace>

编辑:

我想这样做的原因是因为我想提供一个自定义的kafka分区器。

    public Builder<K, V> withCustomPartitionner(Class<? extends Partitioner> customPartitioner) {
        this.customPartitioner = customPartitioner;
        return this;
    }

最佳答案

看起来您希望能够调用给定参数的方法。在这种情况下,您将需要界面的实际实例,而不是与其关联的类。

public void callDoSomething(myInterface myVar) {
    System.out.println(myVar.doSomething());
}

Class<> 当您想要使用反射对您感兴趣的特定类类型执行某些操作时使用:

public void outputClassInfo(Class<? extends myInterface> myClass) {
    System.out.println(myClass.getName());
}

如果这就是您想要的,您将需要在编译时提供该类,如下所示:

outputClassInfo(myInterfaceImpl.class);

或者,如果您直到运行时才知道正在处理哪个类,则可以使用反射:

myInterface thing = getThing();
outputClassInfo(thing.getClass());

因此,在您在编辑中提供的示例中,我猜您想要:

public Builder<K, V> withCustomPartitioner(Class<? extends Partitioner> customPartitioner) {
    this.customPartitioner = customPartitioner;
    return this;
}

// Usage
builder
    .withCustomPartitioner(FooPartitioner.class)
    ...

关于java - 如何满足参数类型Class<?在java中扩展someInterface>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336980/

相关文章:

java - BubbleSort - 我的代码返回随机地址

C#语法糖重载

c# - 通用方法采用 KeyValuePair。如何将调用转发到采用 Key 类型的正确重载?

c# - 使用未知数量的未知类型 - .NET

Java CompletableFuture 分配执行器

Java Streams TakeUntil 过滤/收集 100 个元素

java - hibernate 5.4.12.Final "The attribute cacheable is undefined for the annotation type NamedQuery",是否不支持cacheable = true?

c# - 带表格的通用 CSV 导出

c++ - 使用具有不同输入参数和不同返回类型的模板的通用函数

java - 每个请求发送两个 servlet 响应