hunterge
hunterge

Reputation: 653

Determining a 'type' in Java

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.

Upvotes: 1

Views: 256

Answers (2)

Amar Magar
Amar Magar

Reputation: 881

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);
    }

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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.)

Upvotes: 12

Related Questions