Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of getClass method

Tags:

java

generics

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.

like image 763
Paul Boddington Avatar asked Mar 22 '15 00:03

Paul Boddington


People also ask

What is the use of getClass () 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 is getClass () getName () in 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. Element Type.

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

getClass() returns the runtime class of the object "this". This returned class object is locked by static synchronized method of the represented class.

Can we override getClass method?

The getClass() MethodYou cannot override getClass .


1 Answers

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

like image 101
yshavit Avatar answered Sep 21 '22 03:09

yshavit