jeudi 10 octobre 2019

Java reflection gets superclass got unexpected result

While learning java reflection, I got some problem when testing getSuperclass()

Below is my test code:

System.out.println(java.io.Closeable.class.getSuperclass());

In my expectation, this line shall print something like AutoClosable because this is the class which Closable extends from. However this turns out to be null. I tried to explain this as Closable locates in java.io while AutoClosable locates in java.lang and getSuperclass() would only search in the package scope.

But this explanation does not make sense if I write like this:

Closeable closeable = () -> {

    };
System.out.println(closeable.getClass().getSuperclass());

The code above results in class java.lang.Object. The result makes this problem more peculiar and hard to understand.

How does java implements this getSuperclass() method and why does not this method return the result which corresponds to its name?





Aucun commentaire:

Enregistrer un commentaire