2

Is is possible to check whether given Object item can be casted to some class? Is there any method which doesn't throw an exception?

Sergey
  • 11,548
  • 24
  • 76
  • 113

1 Answers1

4

Yes, Class.isInstance(Object) and the related Class.isAssignableFrom(Class)

Example:

Object x = "foo";
Integer.class.isInstance(x); // => false
Integer.class.isAssignableFrom(x.getClass()); // => false

Edit: You said "method" so I assumed you meant an API method, but if you know the types at compile-time then you can simply use

x instanceof Integer // => false

(see also What is the 'instanceof' operator used for?)

Community
  • 1
  • 1
finnw
  • 47,861
  • 24
  • 143
  • 221