Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getClass return a Class<? extends |X|>?

Tags:

java

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 which getClass 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!
like image 958
Aviel Fedida Avatar asked Jun 13 '16 18:06

Aviel Fedida


People also ask

What does the getClass method return?

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.

What does getClass method do in Java?

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.

What does getClass () getName () Do Java?

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.

What is the purpose of public final class getClass ()?

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.


1 Answers

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().)

like image 92
Louis Wasserman Avatar answered Oct 21 '22 05:10

Louis Wasserman