Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics issue with Class

Tags:

java

generics

Can't figure out this generics 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:

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

I am able to compile if I remove the type params for LoadableObjectFactory at the definition of _cls, but then it's an incomplete type... Is there something I'm missing or is it simply impossible?

like image 926
inkredibl Avatar asked Jul 27 '26 16:07

inkredibl


1 Answers

getClass() in runtime provides Class<?>. Because of type erasure information about generic params is not available. You have to do a cast

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

to get it working

like image 124
Mirek Pluta Avatar answered Jul 30 '26 05:07

Mirek Pluta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!