Working with the class keyword in Java

后端 未结 8 1312
梦毁少年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:23

    A class is a "blueprint" of the object. The instance is a object.

    If we have

    public class SomeClass {
       int a;
       SomeClass(int a) {
          this.a = a
       }
    }
    

    We can have an instance of this class

    SomeClass c = new SomeClass(10);
    

    c is an instance of the class. It has a integer a with value 10.

    The object SomeClass.class represents a Class.

    Here SomeClass.class is a object of the type Class which has the information that SomeClass is

    1. a concrete class with
    2. one constructor
    3. with a integer member variable

      and lots more other metadata about the class SomeClass. Note that it does not have a value for a.

    You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.

    You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.

提交回复
热议问题