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.
java generics
Paul boddington
source share