2013-11-20 49 views
-2

好了,說我有一個類:檢查參數是的instanceof指定的泛型類型

public class Example<E extends Something> { 

public Something s; 
public E e; 

public Example(E e, Something s) { 
    this.e = e; 
    this.s = s; 
} 

} 

,並在另一個I類有:

public Something a = new ExtendsSomething(); 
public Something b = new AlsoExtendsSomething(); 
//Assume I have many more classes that also extend Something, so I cannot do instanceof 
//for each class 
public Example<ExtendsSomething> example1 = new Example<ExtendsSomething>(a); 
public Example<ExtendsSomething> example2 = new Example<ExtendsSomething>(b); 

我會在構造函數中寫什麼代碼在第二類的第6行拋出一個錯誤,因爲b不是ExtendsSomething的一個實例?

+1

沒有什麼可以擴展的字符串,因爲它是一個'final'類,所以你的例子通常綁定的''是荒謬 – Bohemian

+0

,即使你是從比'String'其他東西延長我也希望它無論如何拋出編譯器錯誤。 –

+0

對不起。我現在編輯了這個問題,所以這不再是問題。 – sunnydan

回答

1

這個問題的標題有答案。

if(b instanceof ExtendsString) 
{ 
    public Example<ExtendsString> example2 = new Example<ExtendsString>(b); 
} 
else 
{ 
    //handle your error case 
} 

如果拋出一個錯誤,也許你要投b

if(b instanceof ExtendsString) 
{ 
    public Example<ExtendsString> example2 = new Example<ExtendsString>((ExtendsString)b); 
} 
else 
{ 
    //handle your error case 
} 
+0

爲了清晰起見,我編輯了我的問題。請再看一遍。 – sunnydan

0

編譯器將拒絕編譯示例程序,因爲Example的構造函數有兩個參數。如果刪除s參數,則編譯器將拒絕該程序,因爲b不是ExtendsSomething的子類,就像您期望的那樣。你不需要在構造函數中做任何其他的事情。

相關問題