I know getClass()
method in java.lang.Object
. But In my application, I know all of my classes. So, What is the actual purpose of using this method?
But In my application, I know all of my classes. So, What is the actual purpose of using this method?
So if you write this, do you still know what the real class of things[0]
is?
Object[] things = new Object[]{
"Hi mum", new Integer(42), /* and a whole bunch more */};
shuffle(things);
In theory, you could work out the class of things[0]
using a long series on instanceof
expressions, but that is painful. This solves the problem.
Class cls = things[0].getClass();
Now, I'll grant you that you don't often need to do this sort of thing. But when you do, the functionality of Object.getClass()
is pretty much indispensable.
And as other answers point out, the getClass()
method is very important for applications that make use of reflection to get around the limitations of static typing.
I guess, the other question is whether the existence of the Object.getClass()
method has any impact on JVM performance. The answer is No. The method is only exposing information that has to be there anyway in order to implement the instanceof
operator. And this information is typically used by the garbage collector.
You're wading into the wonderful world of Reflection. Using reflection, you can programmatically inspect classes, set their fields, call their methods, etc. You can do some really powerful stuff with it, and most frameworks that you use on a daily basis (e.g. Hibernate, Spring, Guice, etc.) depend very heavily on it to make things happen.
getClass()
is a public method on Object, so it's inherited for all instances of all classes. If you are dealing with a super type of some sort (a super class or interface etc) and you want to know the implementation class, getClass()
will tell you the class of any object. You can then inspect the class to find out more information.
A simple example:
public static void doSomething(Object obj) {
if (obj.getClass().isArray()) {
System.out.println("It's an array");
} else {
System.out.println("It's not an array");
}
}
btw, getClass()
itself isn't part of reflection - it's a straightforward method that returns a straightforward (class) object. However, the class object returned from getClass()
can be used with reflection (see the java.lang.reflect
package) to find out lots of interesting things about the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With