tags:

views:

1539

answers:

5
+4  Q: 

Java Class Type

I have a block of code that works and I wanted to ask what exactly is happening here?

Class<?> normalFormClass = null;

---added---

The wildcard "<?>" is the part that is confusing for me. Why would this be used rather than not using it (generics)?

A: 

I doubt this is homework, since I've never been in a class that talked about reflection.

But this is a simple null assignment. It doesn't do anything.

Pyrolistical
+4  A: 

That means it can be a Class of any type. ? is a wildcard denoting the set of all types, or 'any'. So you can later do

Integer normalForm = new Integer();
normalFormClass = normalForm.getClass();

or

String normalForm = new String();
normalFormClass = normalForm.getClass();

If you are not aware of generics on Java, read http://java.sun.com/developer/technicalArticles/J2SE/generics/

As for the why, I think it might be to strictly express that you are using generics everywhere and your code is not compatible with older Java versions, or maybe to shut up some trigger happy IDEs. And yes,

Class foo

and

Class<?> foo

are equivalent.

Vinko Vrsalovic
Great example! I'm still learning the basics of Java and have always wondered about lines of code with these brackets.
EnderMB
Thanks Yes... I am aware of generics but the ? wildcard was the thing that I wanted to make sure I fully understood.
pn1 dude
Except you can't create a new Class like that ;) Maybe normalFormClass = obj.getClass();
erickson
I was assuming Class in the original example meant 'foo'. Fixed the example
Vinko Vrsalovic
Thanks this is much clearer now!
pn1 dude
+2  A: 

Class or Class<?> works equally well. One reason to use the latter is to get rid of a few warnings the ide or compiler would throw at you when using the first form.

John Nilsson
Got it and it makes sense
pn1 dude
+2  A: 

Also, the generic version

Class<?> normalClass = null;

is pretty much equivalent to the raw type version,

Class normalClass = null;

the main difference is that the latter will be compatible with versions of Java that do not support generics, like Java 1.4.

John in MD
And thus it can be used to make it clear you are not writing 1.4 compatible code, for example.
Vinko Vrsalovic
Thanks this is much clearer
pn1 dude
+2  A: 

Class<T> means that since JDK 1.5, Class is generified by the type the class defines. One way to think about this is that Class is a factory for creating instances of its type.
Specifically, a Class<T> creates instances of type T from the Class.newInstance() method.

From JDK 1.5 on, it is recommended by the Java Language Spec that you should not use raw types. So, it is highly recommended that when dealing with a Class instance of unknown type, you should refer to it as "Class<?>" and not just "Class". Of course, if you actually know the type or some bound, you might find some benefits of specifying it.

Alex Miller