mercredi 15 mars 2023

In Java, how does one cast Class references (if possible)?

Let me setup the problem:

I am working with an API, lots of inheritance going on. It is very useful to pass around and work with Class type objects (e.g. String.class instead of an instance of String). It is also useful to range check the Class objects when working with them, so a method might have a parameter like this:

public void doSomething(Class<? extends GreatGrandParentClass> typeObject)
{ ... }

The problem is that the GreatGrandParentClass has A LOT of children, grandchildren, and great-grandchildren. So there are times when the type object passed as a parameter, or in a Collection, or whatnot, is a descendant of GreatGrandParentClass, but I'd like to cast the typeObject to it's actual type after confirming it's of that type. E.g.:

public void doSomething(Class<? extends GreatGrandParentClass> typeObject)
{
    Class thisType;
    if (FavoriteCousin.class.isAssignableFrom(typeObject))
        thisType = (FavoriteCousin) typeObject;
    ...
}

And then I use thisType as a parameter to a method that wants a Class object of FavoriteCousin type:

public void needsCousin(Class<? extends FavoriteCousin> cousinType)
{ ... }

But if I try to cast like I do above, I get:

Incompatible types: Class<CAP#1> cannot be converted to FavoriteCousin where CAP#1 is a fresh-type variable:
CAP#1 extends GreatGrandParentClass from capture of ? extends GreatGrandParentClass

Now, I rather expected that the way I did the cast was not correct, but I'm wondering if there is a correct to do that kind of cast, if possible?





Aucun commentaire:

Enregistrer un commentaire