How to determine an object's class?

后端 未结 11 998
醉酒成梦
醉酒成梦 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:23

    I use the blow function in my GeneralUtils class, check it may be useful

        public String getFieldType(Object o) {
        if (o == null) {
            return "Unable to identify the class name";
        }
        return o.getClass().getName();
    }
    
    0 讨论(0)
  • 2020-11-22 17:27

    Use Object.getClass(). It returns the runtime type of the object.

    0 讨论(0)
  • 2020-11-22 17:33
    if (obj instanceof C) {
    //your code
    }
    
    0 讨论(0)
  • 2020-11-22 17:33

    You can use getSimpleName().

    Let's say we have a object: Dog d = new Dog(),

    The we can use below statement to get the class name: Dog. E.g.:

    d.getClass().getSimpleName(); // return String 'Dog'.

    PS: d.getClass() will give you the full name of your object.

    0 讨论(0)
  • 2020-11-22 17:34

    There is also an .isInstance method on the "Class" class. if you get an object's class via myBanana.getClass() you can see if your object myApple is an instance of the same class as myBanana via

    myBanana.getClass().isInstance(myApple)
    
    0 讨论(0)
  • 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 <T> 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 []
    
    0 讨论(0)
提交回复
热议问题