Java's reflection mechanism

I. Introduction reflection

  Java programs, all objects are of two types: compile-time type and run-time type , and a lot of time to compile and run-time type of the object is inconsistent type.

  For example: Some of our variables or parameter of type Object type, but the program does run-time type of the object method needs to be called, the method is not Object methods, how to solve it?

  To solve these problems, the program needs to find real information objects and classes at runtime, we have two methods:

  (1) is in a first compilation and runtime are fully aware of the specific types of information, in this case, we can directly use the instanceof operator to judge, and then use a cast operator converts into run-time type the variable.

  (2) The second is impossible to predict when compiling information for the real objects and classes, the program can only rely on run-time information to discover the real information about the objects and classes, which must be reflected.

  Because after finished loading classes, methods in the heap memory area produces a Class object type (only one of a class Class object), the object contains the complete structural information classes. We can see the structure of the class through this object. This object is like a mirror, see the structure of the class through this mirror, so we called the image: reflection .

Second, reflection: a frame design of the soul

  Framework : is a semi-finished products can be used for the software we use. Software can be developed on the base frame, to simplify the encoding.

  Reflection : The various components of the package as the other objects of the class, this is the reflection.

    Benefits :

      (1) during a program's operation, the operation of these objects.

      (2) can be decoupled, the provider scalability.

  Java code in three stages:

Third, use

  1, by reflection type See

  2, the operation target by reflection and generating

 

Guess you like

Origin www.cnblogs.com/niujifei/p/12311860.html