Skip to main content

APIzation: Replication Package

[Q#17759768][A#17759946] How can check if we can cast an object to another

https://stackoverflow.com/q/17759768

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: How can I check if it can be true or false? It is in java.

Answer

https://stackoverflow.com/a/17759946

Something like this :-

APIzation

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");
    }
}
package com.stackoverflow.api;

import java.util.ArrayList;

public class Human17759946 {

  public static boolean checkConvertable(Object obj) {
    //    ArrayList<Character> obj = new ArrayList<Character>();
    if (
      obj instanceof java.util.ArrayList
    ) //        System.out.println("My problem Solved");
    return true;
    return false;
  }
}

package com.stackoverflow.api;

import java.util.ArrayList;

/**
 * How can check if we can cast an object to another
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/17759946">https://stackoverflow.com/a/17759946</a>
 */
public class APIzator17759946 {

  public static void check() {
    ArrayList<String> ar1 = new ArrayList<String>();
    ArrayList<Character> obj = new ArrayList<Character>();
    if (obj instanceof java.util.ArrayList) System.out.println(
      "My problem Solved"
    );
  }
}