1

Im new to Java, is there a method in Java that tells you the type of an Object?

For example in Python if you type

type(34) it would return int

type('abc') would return string

I've been looking everywhere but I can't find a way of doing it. Any help?

Thanks a lot.

Leo
  • 37,640
  • 8
  • 75
  • 100
hunterge
  • 657
  • 2
  • 10
  • 15
  • 1
    Class cls = obj.getClass(); or you can do the other way around, for instance: if (obj instanceof String) { ... } – gmaliar Dec 29 '12 at 17:13
  • try http://stackoverflow.com/questions/3993982/how-to-check-type-of-variable-in-java – URL87 Dec 29 '12 at 17:13

2 Answers2

12

The instanceof operator is the handiest way to do runtime type checking:

if (someObject instanceof String) {
    // It's a string
}

Alternately, on any instance, you can use getClass, which gives you the Class instance for the type of the object.

Class c = someObject.getClass();

The Class instance will have a getName method you can call to get a string version of the name (and lots of other handy methods).

You can get a Class object from a type name using .class, e.g.:

Class stringClass = String.class;

As Peter Lawrey points out in the comments, all of these assume you're dealing with an object reference, not a primitive. There's no way to do a runtime type check on a primitive, but that's okay, because unlike with object references (where your compile-time declaration may be Object), you always know what your primitive types are because of the declaration. It's only object types where this really comes up.


If you find yourself doing a lot of explicit type checks in your Java code, that can indicate structure/design issues. For the most part, you shouldn't need to check type at runtime. (There are, of course, exceptions.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @PeterLawrey: Good point, I've added a bit on that (wouldn't mind your expert eye cast over the addition, actually, if you have a sec). – T.J. Crowder Dec 29 '12 at 17:21
0

Basically we can achieve our goal by using the method overriding

   class GetType {
        void printType(byte x) {
            System.out.println(x + " is an byte");
        }
        void printType(int x) {
            System.out.println(x + " is an int");
        }
        void printType(float x) {
            System.out.println(x + " is an float");
        }
        void printType(double x) {
            System.out.println(x + " is an double");
        }
        void printType(char x) {
            System.out.println(x + " is an char");
        }
    } 
    public static void main(String args[]) {
          double doubleVar = 1.5;
          int intVar = 7;
          float floatVar = 1f;

          GetType objType = new GetType();
          objType.printType(doubleVar);
          objType.printType(intVar);
          objType.printType(floatVar);
    }
Amar Magar
  • 840
  • 1
  • 11
  • 15