Java: will not compile - incompatible types that should be compatible

This code won't compile and I don't understand why. The error is listed on the specified line:

   static <T extends DB> T createModelObjectFromCopy(T fromRow) {
            T mo = null;
            try {
   -->          mo = fromRow.getClass().newInstance();
            } catch (InstantiationException | IllegalAccessException ex) {
                Logger.getLogger(DBTypes.Table.class.getName()).log(Level.SEVERE, null, ex);
            }
            return Table.initializeFromCopy(mo, fromRow);
        }
    }

      

fromRow

- a value object that wraps immutable types.

It is clear from the declaration that the fromRow

type should be T

. The variable mo

must be of the same type T

.

Why can't a new object with a reflective instance be attached to mo

? I am assuming that the class object returned fromRow.getClass()

is equal Class<T>

, and that newInstance()

-should be an instance of the new instance T

.

+3


source to share


2 answers


The problem is what fromRow.getClass()

returns Class<? extends DB>

, not Class<T>

: the compiler doesn't know enough to draw an output.

Since you know the result will be of the correct type, you can use cast to force the conversion. There are two ways to do this:

Class<T> cl = (Class<T>)fromRow.getClass();
mo = cl.newInstance();

      



or

mo = (T)fromRow.getClass().newInstance();

      

+5


source


This is because of the type erasure - the JVM runtime will not know the type fromRow

; at that point in the code that the JVM (compiler) can only assume that this is something that DB can extend. Hence, you need to do what the other answers suggest (cast or pass the exact type).



+3


source







All Articles