[英]Is this a best practice example of determining the runtime type of Java wildcard <?> referee
我的測試表明,Java反射無法確定在運行時分配給使用通配符聲明的通用對象引用的對象類型。 為了克服這個問題,我寫了以下內容。 如何改進? 對於初學者,當我聲明一個Class對象時,我得到一個原始類型的抱怨但是這不是一個確定分配給通配符引用的運行時類型的最佳實踐示例?
class TestRuntimeType
{
public static void main(String... args) throws Exception
{
Map<Integer, Inventory<?>> map = new HashMap<Integer, Inventory<?>>();
Inventory<Shirt> janesShirts = new Inventory<Shirt>(new Shirt());
janesShirts.add(new Shirt("jack", 17));
map.put(0, janesShirts);
CConsole.myPW.format("%s\n", map.get(0).getElementType());
}
}
class Inventory<T> extends ArrayList<T>
{
private Class elementType;
Inventory(T example)
{
elementType = example.getClass();
}
Class getElementType()
{
return elementType;
}
}
class Shirt
{ String maker; double size;
Shirt() {}
Shirt(String maker, double size)
{ this.maker = maker; this.size = size; }
}
指定類的最佳方法是使用該類。 為了避免必須兩次上課,你可以使用工廠。
class Inventory<T> extends ArrayList<T> {
private final Class<T> elementType;
private Inventory(Class<T> elementType) {
elementType = elementType;
}
public Class<T> getElementType() {
return elementType;
}
public static <T> Inventory<T> of(Class<T> elementType) {
return new Inventory<T>(elementType);
}
}
// later
Inventory<MyType> inv = Inventory.of(MyType.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.