【问题标题】:Intellij is giving strange error. Java Generics issueIntellij 给出了奇怪的错误。 Java泛型问题
【发布时间】:2015-01-21 15:59:55
【问题描述】:

我想从字符串生成一个对象,我还希望生成的对象是扩展 IObject 的 IObjectImpl 类型。

所以,我有一个工厂类方法,它接受一个字符串和一个接口类(比如扩展 IObject 的 IObjectImpl.class,这是强制性的)。该方法应自动检测从字符串(使用反射)类型生成的对象是 IObject 并将其转换为 IObjectImpl。

我编写了以下代码进行测试。但是,Intellij 没有显示错误,同时在我运行 main 方法时,我得到了最后显示的错误。

public <T extends IObject, E extends T> E getInstanceOfType(String clazz, Class type) {
    try {
        System.out.println("Type got is " + type);
        return null;
    } catch (Exception exception) {
        throw new ObjectInstantiationException(String.format("Could not create the "
                + "instance of type %s", clazz), exception);
    }
}

public static void main(String[] args) {
    new Factory().getInstanceOfType("Some class", IObjectImpl.class);
}

错误是:

    Error:(67, 49) java: ..path\Factory.java:67: incompatible types; inferred type argument(s) com.myCompany.IObject,java.lang.Object do not conform to bounds of type variable(s) T,E
found   : <T,E>E
required: java.lang.Object

至于检查类型,我只知道 eClass.isAssignableFrom(tClass) 方法。

我的最终目标是我应该能够调用IObjectImpl 中定义的方法而无需任何强制转换。如何使用 Java 1.6 做到这一点?

【问题讨论】:

标签: java generics intellij-idea


【解决方案1】:
public class Factory {
    public <T extends IObject, E extends T> E getInstanceOfType(String clazz, Class<E> type) {
        try {
            System.out.println("Type got is " + type);
            return null;
        } catch (Exception exception) {
            throw new RuntimeException(String.format("Could not create the "
                    + "instance of type %s", clazz), exception);
        }
    }

    public static void main(String[] args) {
        new Factory().<IObject, IObjectImpl>getInstanceOfType("Some class", IObjectImpl.class);
    }
}

【讨论】:

  • 在你之前 6 分钟发布的一个很好的答案副本 :)
  • 不用担心。对于未来 - 请参阅页面顶部。如果它显示“已发布此问题的新答案”,请在发布您自己的答案之前单击以刷新。这将有助于避免重复:)
【解决方案2】:

你可以像这样指定类型:(java 6)

public static void main(String[] args) {
    new Factory().<IObject, IObjectImpl> getInstanceOfType("Some class", IObjectImpl.class);
}

【讨论】:

  • 它以独立的方式工作。我可以连接同一个工厂作为 bean 并使用 spring 到达其他地方吗?
  • 谢谢。通过像 Class 这样在 Class 上提供泛型没有问题。我认为弹簧也可以接线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 2015-07-15
相关资源
最近更新 更多