2017-05-14 101 views
-2

我寫這是傳遞一個Class作爲參數的方法,像這樣:指定一個類參數必須實現一個特定的接口

public void doStuff(Class<?> clazz) { 
    /* do stuff */ 
} 

然後我可以調用的方法是這樣的:

doStuff(FooBar.class); 

我該如何在編譯器級強制參數只能是實現特定接口的類?

我已經試過以下各項

public <T extends FooInterface> void doStuff(Class<T> clazz) { 
    /* do stuff */ 
} 

- 但得到下面的語句編譯錯誤:

doStuff(FooBar.class); // FooBar implements FooInterface 

如何正確地做到這一點?

+1

後一個完整的小例子,重現問題,併發布準確和完整的編譯錯誤。 –

+0

向我們展示'FooBar'類 – Sweeper

+1

明白了 - 代碼本身是可以的,編譯錯誤是關於未捕獲的異常。圍繞實際方法調用的try/catch塊修復了它。謝謝! – user149408

回答

1

我試過你的聲明,但它似乎工作。請看下面的代碼。我不知道確切的類定義,但在這裏,在這種情況下

t.doStuff(Foo.class) 

的作品,但

t.doStuff(Faa.class) 

public class Test{ 
public <T extends FooInterface> void doStuff(Class<T> clazz) { 
    /* do stuff */ 
} 

public static void main(String[] args) { 
    Test t = new Test(); 
    t.doStuff(Foo.class); //This one compiles fine 
    //g.doStuff(Faa.class); <-- This line gives error 
} 
} 

interface FooInterface{ 

} 

class Foo implements FooInterface{ 

} 

class Faa{ 

} 
+0

應該更仔細地查看編譯器錯誤 - 代碼正常,錯誤無關,請參閱上文。 – user149408

+0

完全贊同:-) –

0

原來我試過的代碼,其實是正確的,並且編譯器錯誤(也就是說,Eclipse強調了紅色的調用)是調用周圍缺少try/catch塊的結果。

有兩種可能的方式來達到預期的效果:

public <T extends FooInterface> void doStuff(Class<T> clazz) { 
    /* do stuff */ 
} 

或者,不太精細:

public void doStuff(Class<? extends FooInterface> clazz) { 
    /* do stuff */ 
} 
相關問題