Problem with Java generics with class

Unable to determine this problem. I have these interfaces:

public interface LoadableObject
{
}
public interface LoadableObjectFactory<T>
{
}

And now I want to do this:

public class ObjectReference<T extends LoadableObject>
{
    Class<? extends LoadableObjectFactory<T>> _cls;

    public ObjectReference(LoadableObjectFactory<T> obj)
    {
        _cls = obj.getClass();
    }
}

But I get an error message:

incompatible types
found   : java.lang.Class<capture#885 of ? extends test.LoadableObjectFactory>
required: java.lang.Class<? extends test.LoadableObjectFactory<T>>
  _cls = obj.getClass();
                     ^

I can compile if I delete the param parameters for LoadableObjectFactoryin the definition _cls, but then it is an incomplete type ... Is there something that I am missing or simply impossible?

+3
source share
4 answers

getClass () at runtime provides the class <? >. Due to the erasure type, general parameter information is not available. You have to throw

    @SuppressWarnings("unchecked")
public ObjectReference(LoadableObjectFactory<T> obj)
{
    _cls = (Class<? extends LoadableObjectFactory<T>>) obj.getClass();
}

to make it work

+4
source

, , , .

, . , , , Java "" , .

, , , , Java, Java- : Scala. Scala ; , . JVM, Scala Java-.

Scala , , , , .:)

+4

. , , .

Java Generics , . , , , , .

+1

, LoadableObjectFactory :

public interface LoadableObjectFactory<T extends LoadableObject>

, - Object.getClass() , . , java.lang.Object

class Object<T extends Object<T>> {
    native Class<T> getClass();
}

java.lang.Object .

0

Source: https://habr.com/ru/post/1724135/


All Articles