What is the difference between Class clazz and Class <?> Clazz in java?

I need to use reflection in java. I understand that Class clazz creates a variable representing a Class object. However, I am trying to reference the Class object from String using the forName("aClassName") method. My IDE (Eclipse) seems to prefer the Class<?> clazz for declaring a variable. I have repeatedly seen this designation elsewhere. What does it mean?

Edit: Removed link to ternary operator as this does not apply to this issue.

+8
java reflection ternary-operator
source share
3 answers

Class is a raw type - it is basically a generic type, which you consider as if you did not know about generics at all.

Class<?> Is a generic type using an unrelated wildcard - it basically means " Class<Foo> for some type of Foo , but I don't know what."

Similarly, you can have wildcards with restrictions:

  • Class<? extends InputStream> Class<? extends InputStream> means " Class<Foo> for some type of Foo , but I don’t know to what extent it is an InputStream or a subclass"

  • Class<? super InputStream> Class<? super InputStream> means " Class<Foo> for some type of Foo , but I don't know to what extent it is an InputStream or a superclass"

For more information, see Java Generics Frequently Asked Questions :

And the Java language specification:

In particular, from the section "Raw Types":

Raw types are closely related to wildcards. Both are based on existential types. Raw types can be thought of as wildcards whose type rules are deliberately unreasonable to allow interaction with legacy code. Historically, the original types were preceded by wildcards; they were first introduced in GJ and described in the article β€œThe Future is Safe for the Past: Adding Versatility to the Java Programming Language” by Gilad Bracha, Martin Odersky, David Stautamir and Philip Wadler in the ACM Conference Proceedings on Object-Oriented Programming, Systems, Languages ​​and Appendices (OOPSLA 98), October 1998

+22
source share

The first thing to understand is that in this case "?" It is NOT a triple operator, but is part of the Java generics implementation and indicates that the class type is not specified, as some of the other answers have already been explained.

To clarify the issue of the ternary operator, this is actually very simple.

Imagine you have the following if statement:

 boolean correct = true; String message; if (correct) { message = "You are correct."; } else { message = "You are wrong."; } 

You can rewrite this with the ternary operator (consider it an if-else-shortcut operator):

 message = (correct) ? "You are correct." : "You are wrong."; 

However, it is best to avoid the triple operator for all but the simplest operators to improve the readability of your code.

+2
source share

In generic types, wildcard ? means "any class" (therefore, Class<?> matches just Class , but as a raw type it is correctly parameterized).

0
source share

All Articles