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?

1
  • Are you referring to the instanceof operator? Commented Nov 11, 2011 at 4:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.