Alexey Andronov Alexey Andronov - 4 months ago 14
Java Question

How to compare two classes

I try to create a factory, here's the code:

public class MyFactory {
public static <T> MyBase create(Class<T> _c) {
if (_c.getClass().equals(Derived1.class)) // (1)
return createNewDerived1();

return null;
}
}

// caller
MyFactory.create(Derived1.class);


It compiles with warning at line
(1)
:

Error



'equals()' between objects of inconvertible types 'Class<Derived1>'
and 'Class<capture of ? extends Class>' <br>Reports calls to .equals()
where the target and argument are of incompatible types. While such a
call might theoretically be useful, most likely it represents a bug.


And in runtime my
if
statement fails for some reason.
How can I get the intended behaviour?

Answer
public class MyFactory {
    public static <T> MyBase create(Class<T> _c) {
        return ( _c == Derived1.class ) ? createNewDerived1() : null;
    }
}

// caller
MyFactory.create(Derived1.class);

See Compare class objects for further info.

FIY, "real" class object references have Class<MyClass> erasures, while the Class returned by .class class is, AFAIR, just rawtype Class on some environments and Class<capture of ?>-ish on others.

Comments