50

How can check if we can cast an object to another?

I have an object that it is an Arraylist of instances of an class that can be dynamically in 2 other class. How can I check that I can cast my object to each of them Arraylist class?

For example:

  • My classes are class1, class2 and class3.
  • My object is obj.

I want check it:

ArrayList<class1> ar1=new Arraylist<class1>();
ar1=(ArrayList<class1>)obj;

How can I check if it can be true or false?

peterh
  • 11,875
  • 18
  • 85
  • 108
user2601734
  • 575
  • 1
  • 5
  • 12
  • 10
    have you ever heard about 'instanceof'? and also "convert" is the correct spelling. – Juvanis Jul 20 '13 at 07:17
  • 1
    Please refer to http://stackoverflow.com/questions/7526817/use-of-instance-of-in-java – John Snow Jul 20 '13 at 07:30
  • 5
    and also 'cast' is the correct term, not 'convert'. – user207421 Jul 20 '13 at 08:26
  • Post linked by John Snow is a good place to start. But instanceof should be hardly needed when application is properly designed - please see extends T> construct - http://stackoverflow.com/questions/897935/when-do-java-generics-require-extends-t-instead-of-t-and-is-there-any-down – Grzegorz Jul 20 '13 at 08:35
  • possible duplicate of [What is the 'instanceof' operator used for?](http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for) – djf Jul 20 '13 at 11:14

1 Answers1

72

Something like this :-

import java.util.ArrayList;

public class qu
{
    public static void main(String args[])
    {
        ArrayList<String> ar1=new ArrayList<String>();
        ArrayList<Character> obj = new ArrayList<Character>();
        if(obj instanceof java.util.ArrayList)
            System.out.println("My problem Solved");
    }
}
John Snow
  • 977
  • 7
  • 12