繁体   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