Java 如何满足参数类型类<;?扩展someInterface>;在爪哇

Java 如何满足参数类型类<;?扩展someInterface>;在爪哇,java,generics,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

考虑以下代码

@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());
}
如何满足参数类型?如果只有一个接口提供给我

我想绑定有接口的类,但这似乎对我不可用

Class<? implements myInterace>

Class您需要传递
Class
而不是实例

callDoSomething(MyInterfaceImpl.class);

您需要传递
而不是实例

callDoSomething(MyInterfaceImpl.class);

callDoSomething
的参数不应该是类。它必须是该类或其子类的实例

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

callDoSomething
的参数不应该是类。它必须是该类或其子类的实例

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

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

public void callDoSomething(myInterface myVar) {
    System.out.println(myVar.doSomething());
}
当您希望使用反射对您感兴趣的特定类类型执行某些操作时使用:

public void outputClassInfo(Class<? extends myInterface> myClass) {
    System.out.println(myClass.getName());
}
或者,如果直到运行时才知道要处理的是哪个类,则可以使用反射:

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)
    ...

public Builder with custompartitioner(Class看起来您希望能够对给定的参数调用方法。在这种情况下,您需要的是接口的实际实例,而不是与其关联的类

public void callDoSomething(myInterface myVar) {
    System.out.println(myVar.doSomething());
}
当您希望使用反射对您感兴趣的特定类类型执行某些操作时使用:

public void outputClassInfo(Class<? extends myInterface> myClass) {
    System.out.println(myClass.getName());
}
或者,如果直到运行时才知道要处理的是哪个类,则可以使用反射:

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)
    ...

带有CustomPartitioner的公共生成器(类作为旁注,类和接口名称应始终以大写字母开头。请查看.ClassAs作为旁注,类和接口名称应始终以大写字母开头。请查看。或者,由于OP正在尝试调用
doSomething
,请将参数
MyInterface myVar
设置为ld使其中一个错误消失,这显然不是OP的意图。或者,由于OP试图调用
doSomething
,使参数
MyInterface myVar
。虽然这会使其中一个错误消失,但显然不是OP的意图。使用类型变量没有好处。直接使用
MyInterface
。@Andy T确实如此。使用类型变量没有好处。直接使用
myInterface
。@Andy Turner确实如此。@Andy Turner Right。更新了我的答案。Thanks@AndyTurner对。更新了我的答案。谢谢