簡體   English   中英

將Java泛型用於簡單工廠-如何避免這些警告

[英]Using java generics for a simple factory - How can I avoid these warnings

我試圖正確地理解泛型,並且編寫了一個非常簡單的工廠,但是我看不到如何避免這兩個警告(我周圍有很多麻煩,但是可能我不是在搜索正確的條件)。 哦! 而且我不想僅僅發出警告-我確信應該可以正確地做到。

  • 類型安全:構造函數simpleFactory(Class)屬於原始類型simpleFactory。 泛型類型simpleFactory的引用應參數化
  • simpleFactory是原始類型。 泛型類型simpleFactory的引用應參數化

我嘗試解決的所有構造實際上都無法編譯-這似乎是我能得到的最接近的構造。 標記為++++的行生成警告(在Eclipse Indigo上為android項目)

我意識到周圍有一些優秀的對象工廠,但這是關於了解語言的知識,而不是實際創建工廠;)

來源如下:

import java.util.Stack;

public class simpleFactory<T> {

private Stack<T> cupboard;
private int allocCount;
private Class<T> thisclass;

public static simpleFactory<?> makeFactory(Class<?> facType) {
    try {
        facType.getConstructor();
    } catch (NoSuchMethodException e) {
        return null;
    }
+++++   return new simpleFactory(facType);
}

private simpleFactory(Class<T> facType) {
    thisclass = facType;
    cupboard = new Stack<T>();
}

public T obtain() {
    if (cupboard.isEmpty()) {
        allocCount++;
        try {
            return thisclass.newInstance();
        } catch (IllegalAccessException a) {
            return null;
        } catch (InstantiationException b) {
            return null;
        }
    } else {
        return cupboard.pop();
    }
}

public void recycle(T wornout) {
    cupboard.push(wornout);
}   
}

因此,重要的部分是您實際上想要捕獲傳遞給工廠方法的類的類型。 我正在使用相同的標識符(T)來隱藏類的類型,這可能會有些混亂,因此您可能想使用其他標識符。

您還需要使用特定類型實例化類,例如提到的cutchin。

public static <T> simpleFactory<T> makeFactory(Class<T> facType)
{
    try
    {
        facType.getConstructor();
    }
    catch (NoSuchMethodException e)
    {
        return null;
    }
    return new simpleFactory<T>(facType);
}

我以前的回答完全被打破了。 這是更好的工廠方法。

public static <R> simpleFactory<R> makeFactory(Class<R> facType) {
    try {
        facType.getConstructor();
    } catch (NoSuchMethodException e) {
        return null;
    }
   return new simpleFactory<R>(facType);
}

用法:

simpleFactory<String> factory = simpleFactory.makeFactory(String.class);

暫無
暫無

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

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