Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get possible instance/type of object

Tags:

java

I have the problem that a given object could be one of several different objects (like files in a directory, that could be sound, image, text, ...) Is there the possibility to find out the type of the object beside from the 'instanceof' operator? Couse that would result in an endless if - then row ...

like image 549
machine Avatar asked Jul 21 '09 14:07

machine


People also ask

How do I find the instance of an object?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How do you know what class an object is?

We can use the isInstance() method to check the class of an object at runtime. Furthermore, isInstance() handles autoboxing as well. When we make use of the isInstance() method, we protect our program from attempting illegal downcasts, although, using the instanceof operator will be smoother in this case.

What is getClass method in Java?

The Java Object getClass() method returns the class name of the object. The syntax of the getClass() method is: object.getClass()

Is there a Typeof in Java?

Java does not have typeof but rather has the getClass(), instanceof and java. lang. Class. isInstance().


1 Answers

foo.getClass() gets the java.lang.Class object describing the class of the object.

like image 122
Joachim Sauer Avatar answered Sep 28 '22 08:09

Joachim Sauer