I need to make use of reflection in java. I understand that Class clazz
creates a variable representing a Class
object. However, I am trying to reference a Class
object from a String
using the forName("aClassName")
method. My IDE (Eclipse), seems to prefer the notation Class<?> clazz
for declaring the variable. I have seen this notation many times elsewhere. What does this mean?
Edit: Removed reference to ternary operator as it is not relevant to this question.
Class
is a raw type - it's basically a generic type that you're treating as if you didn't know about generics at all.
Class<?>
is a generic type using an unbound wildcard - it basically means "Class<Foo>
for some type Foo
, but I don't know what".
Similarly you can have wildcards with bounds:
Class<? extends InputStream>
means "Class<Foo>
for some type Foo
, but I don't know what so long as it's InputStream
or a subclass"
Class<? super InputStream>
means "Class<Foo>
for some type Foo
, but I don't know what so long as it's InputStream
or a superclass"
See also the Java Generics FAQ for a lot more information:
And the Java Language Specification:
In particular, from the raw types section:
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 unsound, to accommodate interaction with legacy code. Historically, raw types preceded wildcards; they were first introduced in GJ, and described in the paper Making the future safe for the past: Adding Genericity to the Java Programming Language by Gilad Bracha, Martin Odersky, David Stoutamire, and Philip Wadler, in Proceedings of the ACM Conference on Object-Oriented Programming, Systems, Languages and Applications (OOPSLA 98), October 1998.
The first thing to realize is that, in this case, the "?" is NOT the ternary operator, but is part of Java's generics implementation and indicates that the type of Class is unspecified, as some of the other answers have already explained.
To clarify the question about the ternary operator, it 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 that with the ternary operator (think of it as the if-else-shortcut operator):
message = (correct) ? "You are correct." : "You are wrong.";
However, it's best to avoid the ternary operator for all but the simplest statements in order to improve the readability of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With