GetClass return method type

The documentation for the getClass() method in Object says:

Actual result type Class<? extends |X|> Class<? extends |X|> where |X| - This erases the static type of the expression on which getClass is called.

So why 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 accepted yshavit's answer as it unambiguously answers my question, but I'm still interested to know why they defined it like that. They could define its type Class<? extends T> Class<? extends T> , where T is the static type of the expression. It is not clear to me why at this stage it is necessary to erase type information. It makes sense if the type is List<String> , but not if it is T I will answer any answer explaining this.

+7
java generics
source share
1 answer

where |X| - erasing the static type of the expression (selection added)

erasure T t - Object , therefore |X| Object in this case. This means that the result type is Class<? extends Object> Class<? extends Object> (which is essentially equivalent to Class<?> ).

Erasing String s , on the other hand, is String (since String is reifiable , i.e. not shared).

+7
source share

All Articles