Java 具有多态性和工厂类的泛型

Java 具有多态性和工厂类的泛型,java,generics,design-patterns,factory-pattern,Java,Generics,Design Patterns,Factory Pattern,我制作了几个类结构,现在我在工厂类中创建它们时遇到了问题。 我有通用接口: interface GenericInterface<T>{ T someMethod(T instance); } 接口通用接口{ T方法(T实例); } 和子类,如: class Class_A implements GenericInterface<String>{ String someMethod(String instance){//impl}; } class Clas

我制作了几个类结构,现在我在工厂类中创建它们时遇到了问题。 我有通用接口:

interface GenericInterface<T>{
  T someMethod(T instance);
}
接口通用接口{
T方法(T实例);
}
和子类,如:

class Class_A implements GenericInterface<String>{
  String someMethod(String instance){//impl};
}

class Class_B implements GenericInterface<Integer>{
  Integer someMethod(Integer instance){//impl};
}
class\u A实现泛型接口{
字符串方法(字符串实例){//impl};
}
类B实现泛型接口{
整数方法(整数实例){//impl};
}
现在的问题是我需要工厂类,比如:

class FactoryClass{
  static <T> GenericInterface<T> getSpecificClass(T instance){
    //errors
    if(instance instanceof String) return new Class_A;
    if(instance instanceof Integer) return new Class_B;
}
class工厂类{
静态GenericInterface getSpecificClass(T实例){
//错误
if(instance instanceof String)返回新类_A;
if(instance instanceof Integer)返回新类_B;
}
在其他地方:

String test = "some text";
GenericInterface<String> helper = FactoryClass.getSpecificClass(test);
String afterProcessing = helper.someMethod(test);
String test=“一些文本”;
GenericInterface helper=FactoryClass.getSpecificClass(测试);
字符串后处理=helper.someMethod(测试);
因此,对于字符串对象作为参数,我应该得到
Class_a
实例,对于Integer,我应该得到
Class_B
实例。 现在我有一个错误,
Class\u A
不是
GenericInterface
的子类型。我可以将Factory类中的返回类型更改为原始类型
GenericInterface
,但它似乎不是解决方案,因为我在整个项目中都收到了警告


你对如何实现这些功能有什么建议吗?可能是使用不同的设计模式?我需要通用的超级接口,因为从你的使用中进一步多态调用了
someMethod()

,我相信你需要这样的接口

interface GenericInterface<T>{
    T someMethod(T input);
}
接口通用接口{
T方法(T输入);
}

现在,您应该有工厂类,如

class FactoryClass {
    static <T, S extends GenericInterface<T>> S getSpecificClass(T instance) {
        if(instance instanceof String) return new Class_A();
        if(instance instanceof Integer) return new Class_B();
        return null;
    }
}
class工厂类{
静态S getSpecificClass(T实例){
if(instance instanceof String)返回新类_A();
if(instance instanceof Integer)返回新类_B();
返回null;
}
}
希望这有帮助。

祝你好运。

不幸的是,类型系统可能无法确定这是类型安全的,并且会发出一些警告甚至错误。你可能是对的,我没有测试这段代码,只是在这里编写了它。我尝试过,正如Marko所说,仍然有一个错误,因此你需要
@SuppressWarnings(“未检查”)
方法,并在所有情况下使用
return(S)new…
。这将对所需的目标类型执行未经检查的强制转换。您可以在FactoryClass中进行强制转换,如下所示:
return(GenericInterface)new Class_a();