I think almost every Java developer was once asked at the interview: “What are the methods of the Object class?”
I, at least, was asked repeatedly. And, if for the first time it was a surprise (I think I forgot about clone), then I was sure that I knew Object's methods;)
And what was my surprise when, after several years of development, I came across my own ignorance of the getClass () method
signatureUnder the cut are a few words about Class, .class, .getClass and, actually, a surprise that I stumbled upon.
')
So, we have class A and an object of this class a:
public class A { } ... A a = new A();
0. A.class vs a.getClass ()
Let's start with the simple. When you call getClass (), polymorphism can work, and the result will be a descendant class.
public class B extends A { { ... A a1 = new B(); a1.getClass();
Hidden textThere was a lie, which I pointed out in the
comments . A class is not a static field, which may seem (and not even a native-pseudo-static field, as I thought), but a special construction of the language. And, unlike a static field, you cannot access it through an object!
a.class;
But it is, flowers. Go ahead.
1. What is this class of yours?
A.class is an object of class Class. Look in Class.java:
public final class Class<T> implements ...
This is a generic. Moreover, it is typed, obviously, by this very A - class, which was called .class
If you think about it, it is clear why this is needed: now, in particular, you can write a method that returns an arbitrary type, depending on the argument:
public <T> T foo(Class<T> clazz);
A.class returns an object of class Class:
Class<A> result = A.class;
2. And what does a.getClass () return?
By putting together all of the above, you can guess that:
Class<A> result1 = a.getClass();
Indeed, in view of polymorphism, one should not forget that the actual class of an object a is not necessarily A — it can be any subclass:
Class<? extends A> result = a.getClass();
3. And what is written in Object.java?
All of these generics are great, of course, but how to write the signature of the getClass method with the java syntax in the Object class?
But nothing:
public final native Class<?> getClass();
And the question why the above example was not compiled will be answered by
Maxim Potashev Javadok to the method:
The actual result type is Class <? extends | X |> where | X | This is an erasure of which getClass is called.
So in Object.java one signature is written, and the compiler substitutes another.