A case for == on Class objects

Sending around Class objects can be useful in some cases. Most people don’t know or bother declaring them with types, and that can work too.

I recently encountered code like this; the method choose was supposed to take Class objects belonging to a certain class hierarchy, and they used .equals() to find what class object it was:

Of course, you get a generics warning in a sensible IDE, so many developers put a clever <?> at the end to ”get rid of the warning”:

What you really should do is use generics properly, for example Class<? extends Number>. The parameter was supposed to belong to a certain class hierarchy, in this case Number.

Why is generics important here? To catch errors like this:

Errors? Yes, clazz should obviously never be String.class here – remember the supposed class hierarchy? However, since the code uses the bad .equals() call on a Class object, no compiler error is generated.

If we, on the other hand, do what we should:

Good, now we get a compiler error! The compiler here helps you determine that this if is problematic. And, if you now try to call the method with a String, you will, of course, also get an error at compile time. No such luck without the proper type.

Help the compiler find bugs for you by using the language properly! Don’t be afraid to use ==! Just know what it does and when to use (and not to use) it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please answer this amazingly complicated math question to prove that you are not a spam bot: