phoenix
phoenix

Reputation: 995

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?

Upvotes: 2

Views: 2346

Answers (2)

Vitaly
Vitaly

Reputation: 2662

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

Upvotes: 3

vikingsteve
vikingsteve

Reputation: 40418

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

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

Upvotes: 2

Related Questions