What instance of the object does this method return?

I wrote a method below, but I need to find the instance objectreturned. I also need to check if this is a type JSONor another return type, will this method work?

public class DynamicObject {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DynamicObject obj = new DynamicObject();

        if(obj.testObj() instanceof String)
            System.out.println("String");
        else if (obj.testObj() instanceof Array)
            System.out.println("Integer Array");
        else if (obj.testObj() instanceof Integer)
            System.out.println("Integer");


    }

    private Object testObj(){
        boolean test = false;
        String s= new String("test");
        Integer in[] = {1,2,3,4,5};
        if(test){
            return s;
        }else{
            return in;
        }
    }

}

What will be the instance of this case. If I run this, the console will not show anything.

+4
source share
4 answers

instanceof must be an integer []

else if (obj.testObj() instanceof Integer[])
            System.out.println("Integer Array");
+3
source

Java arrays are not subclasses of java.lang.reflect.Array.

In other words, the integer array FIX test

(obj.testObj() instanceof Array)
+2
source

testObj() , Java Integer[]. main() String, Array Integer, .

If you were to change the second test from Arrayto Integer[], it would work as you expected:

else if (obj.testObj() instanceof Integer[])
    System.out.println("Integer Array");

Reason for use obj.testObj() instanceof Arraydoes not work, because the class java.lang.reflect.Arrayis not really a superclass of Java arrays. According to the JavaDoc page, the class "provides static methods for dynamically creating and accessing Java arrays" - this is not the array itself, it is just a utility for creating and accessing arrays.

+1
source

Get object type:

Class cls = obj.testObj().getClass(); 
System.out.println("The type of the object is: " + cls.getName());
0
source

All Articles