How to determine an object's class?

后端 未结 11 1183
醉酒成梦
醉酒成梦 2020-11-22 17:10

If class B and class C extend class A and I have an object of type B or C, how can I determine of which type

11条回答
  •  半阙折子戏
    2020-11-22 17:38

    I Used Java 8 generics to get what is the object instance at runtime rather than having to use switch case

     public  void print(T data) {
        System.out.println(data.getClass().getName()+" => The data is " + data);
    }
    

    pass any type of data and the method will print the type of data you passed while calling it. eg

        String str = "Hello World";
        int number = 10;
        double decimal = 10.0;
        float f = 10F;
        long l = 10L;
        List list = new ArrayList();
        print(str);
        print(number);
        print(decimal);
        print(f);
        print(l);
        print(list);
    

    Following is the output

    java.lang.String => The data is Hello World
    java.lang.Integer => The data is 10
    java.lang.Double => The data is 10.0
    java.lang.Float => The data is 10.0
    java.lang.Long => The data is 10
    java.util.ArrayList => The data is []
    

提交回复
热议问题