考虑以下代码
@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/