簡體   English   中英

如何滿足參數類型Class <? extends someInterface> 在java中

[英]How to satisfy parameter type Class<? extends someInterface> in java

考慮以下代碼

@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>

我如何滿足參數類型? 如果僅提供接口給我。

我想綁定具有接口的類,但是看來這對我不可用

Class<? implements myInterace>

編輯:

我想這樣做的原因是因為我想提供一個自定義的kafka分區程序。

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

看來您希望能夠在給定的參數上調用方法。 在這種情況下,您將需要接口的實際實例,而不是與之關聯的Class。

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

callDoSomething的參數不應為類。 它必須是該類的實例或其子類。

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

附帶說明一下,請勿以小寫字母命名Java類/接口。

正如安迪·特納(Andy Turner @)正確提到的,此處無需使用類型參數,您可以將類型稱為myInterface

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

此類型Class<? extends myInterface> myVar Class<? extends myInterface> myVar對應於Class實例,而不對應於myInterface的實例。
通常,您不將類作為參數傳遞(但出於反射目的或繞過泛型擦除)。 因此,您需要作為參數的可能是:

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

您可以調用:

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

您需要傳遞Class而不是實例。

callDoSomething(MyInterfaceImpl.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM