I tried to understand what is the reason for getClass
method to return Class<? extends |X|>
?
From the openjdk near public final native Class<?> getClass();
:
The actual result type is
Class<? extends |X|>
where|X|
is the erasure of the static type of the expression on whichgetClass
is called.
Why can't getClass
have the same type such as XClass.class
, for example:
class Foo {}
Foo fooInstance = new Foo();
Class<Foo> fc = Foo.class; // Works!
Class<Foo> fc2 = fooInstance.getClass(); // Type mismatch ;(
Class<?> fc3 = fooInstance.getClass(); // Works!
Class<? extends Foo> fc4 = fooInstance.getClass(); // Works!
getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
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.
getClass() in Java is a method of the Object class present in java. lang package. getClass() returns the runtime class of the object "this". This returned class object is locked by static synchronized method of the represented class.
Foo foo = new SubFoo();
What do you expect foo.getClass()
to return? (It's going to return SubFoo.class
.)
That's part of the whole point: that getClass()
returns the class of the real object, not the reference type. Otherwise, you could just write the reference type, and foo.getClass()
would never be any different from Foo.class
, so you'd just write the second one anyway.
(Note, by the way, that getClass()
actually has its own special treatment in the type system, not like any other method, because SubFoo.getClass()
does not return a subtype of Foo.getClass()
.)
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