Working with the class keyword in Java

后端 未结 8 1311
梦毁少年i
梦毁少年i 2021-02-13 19:16

I don\'t really understand how the class keywords work in some instances.

For example, the get(ClientResponse.class) method takes the Cl

8条回答
  •  盖世英雄少女心
    2021-02-13 19:47

    In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.

    The keyword is the one that we use to define a class in Java. e.g.

    public class MyClass { } /* class used here is one of the keywords in Java */
    

    The class in ClientResponse.class is a short-cut to the instance of Class that represents the class ClientResponse.

    There is another way to get to that instance for which you need an instance of ClientResponse. e.g

    ClientResponse obj = new ClientResponse();
    Class clazz = obj.getClass(); 
    

    what are the advantage over just passing a instance of it?

    In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.

提交回复
热议问题