Working with the class keyword in Java

后端 未结 8 1318
梦毁少年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:46
    SomeClass.class
    

    returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .

    There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html

    0 讨论(0)
  • 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<T> 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.

    0 讨论(0)
提交回复
热议问题