Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need the method getClass() from java.lang.Object?

Tags:

java

oop

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?

like image 942
Saravanan Avatar asked Sep 13 '11 07:09

Saravanan


3 Answers

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.

like image 180
Stephen C Avatar answered Nov 08 '22 00:11

Stephen C


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.

like image 25
stevevls Avatar answered Nov 08 '22 01:11

stevevls


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.

like image 2
Bohemian Avatar answered Nov 08 '22 02:11

Bohemian