简体   繁体   中英

Intellij is giving strange error. Java Generics issue

I want to produce an object from a string, I also want that produced object to be of type IObjectImpl that extends IObject.

So, I have a factory class method that takes a string and an interface class(say IObjectImpl.class that extends IObject, which is mandatory). That method should automatically detect that the object produced from string(using reflection) type is IObject and cast it to IObjectImpl.

I have written the following code for testing. But, Intellij does not show error and at the same time while I run the main method, I get the error shown at the end.

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);
}

The error is:

    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

As far as checking type, I just know about eClass.isAssignableFrom(tClass) approach.

My final goal is that I should be able to call the methods defined in IObjectImpl without any cast. How can I do it using Java 1.6?

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);
    }
}

You can specify the types like this: (java 6)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM