This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
David only indirectly pointed out the problem with your assumptions, so I'll make it explicit: Integer.TYPE is actually a special pseudo-class representing "int", while Integer.class would be the class representing java.lang.Integer. They're different types, obviously. Every class has a fake ".class" member like this.
Personally I've never had a need for the TYPE field, as I just use the corresponding .class notation instead. But I suppose it might be useful if you've got a Class object representing a wrapper class, and need to find the corresponding primitive type.
Ernest Friedman-Hill wrote:while Integer.class would be the class representing java.lang.Integer. They're different types, obviously.
though very similar and easily confused
Ernest Friedman-Hill wrote:Every class has a fake ".class" member like this.
Every class does, and every interface, and every primitive. And even a void return type is represented by Void.class and void.class. It's very confusing - the Class class has a very misleading name, since it really represents more than just classes. And for primitive types there are two closely-related Class objects - one for the primitive itself, and one for the wrapper.
I think calling this "fake" is also misleading. Both int.class and Integer.class represent real Class objects in the JVM. But there is no member variable called "class". I guess that's what EFH meant by "fake .class member". I just wanted to point out that it's not a member, but it is real.
Dan Hop wrote:lets say the return type is of Type String?
how would I test for that..String does not have a 'TYPE' field?
Just use String.class. For most classes this is all you need, the .class object. Primitives are more complex, because there's a .class for the primitive itself (like int.class) and a .class for the wrapper class for the primitive (like Integer.class). And you need to pay attention to which is which. But for other classes like String, there are no corresponding primitive classes, and the regular Class object (like String.class) is all you need.
No, I was intentionally referring to the fact that there are two different Class objects, void.class and Void.class, which represent the concept of a void return type. The one returned by getReturnType() is void.class, but Void.class does exist too, so I mentioned it. I can't think of a good use for Void.class, but I have seen Void used as a type parameter - Callable<Void> for example.