The documentation for the method getClass()
in Object
says:
The actual result type is
Class<? extends |X|>
where|X|
is the erasure of the static type of the expression on which getClass is called.
So why does foo
compile but not bar
?
static void foo(String s) {
try {
Class<? extends String> clazz = s.getClass();
} catch (Exception e) {
}
}
static <T> void bar(T t) {
try {
Class<? extends T> clazz = t.getClass();
} catch (Exception e) {
}
}
Edit
I've accepted yshavit's answer, as it clearly answers my question, but I'm still curious to know why they defined it like this. They could have defined it to have type Class<? extends T>
where T
is the static type of the expression. It isn't clear to me why it's necessary to erase the type information at this stage. It makes sense if the type is List<String>
, but not if it's T
. I'll up-vote any answer that explains this.
The getClass() method of Writer Class in Java is used to get the parent Class of this Writer instance. This method does not accepts any parameter and returns the required Class details. Parameters: This method accepts does not accepts any parameter.
Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
getClass() returns the runtime class of the object "this". This returned class object is locked by static synchronized method of the represented class.
The getClass() MethodYou cannot override getClass .
where
|X|
is the erasure of the static type of the expression (emphasis added)
The erasure of T t
is Object
, so |X|
is Object
in that case. That means that the result type is Class<? extends Object>
(which is essentially equivalent to Class<?>
).
The erasure of String s
, on the other hand, is String
(since String
is a reifiable type -- ie, not generic).
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