Java Learning: Introduction to reflection

What is reflection

Reflection mechanism is in the operating state, for any class, are made known to all the properties and methods of this class;

For any object, we are able to call any of its methods and properties;

This method of function and dynamic information call the object's reflection mechanism known as dynamic acquisition of java language .

Popular speak, by reflection, the class is completely transparent to us, you want to get anything can be.

What do reflection

The main reflection mechanism provides the following features:

  1. Determining at runtime object belongs to any class;
  2. At runtime class of an object in any configuration;
  3. Analyzing any class has member variables and methods at runtime;
  4. Call any of the object's method at run time;
  5. Generate dynamic proxy.

Use of reflection

Want to use reflection, we must first get to the class bytecode file object (.class), it is possible to get through this kind of method to all the information (by the way we want bytecode file object , property, class name, the name of the parent class, etc. all interfaces implemented), each corresponding to a class bytecode files also correspond to a class Object type, i.e. bytecode file object.

Get bytecode file object in three ways.

1, Class clazz1 = Class.forName ( "fully qualified class name");  // static method forName Class class, directly into a bytecode file object class, then the class source file, or stage, and no changes to bytecode files. 

. 2, Class clazz2 = Person class ;    // when the class is loaded into .class files, this time into a .class Person class, acquiring the bytecode file object, i.e. gets its own, in such bytes code phase. 

. 3, Class clazz3 p.getClass = ();    // instance by acquiring the class object of the class bytecode files, class objects created in stage 

GetDeclaredFields and the difference getFields

  • Field getDeclaredFields () to get all declare a class, that includes public, private and proteced, but does not include the stated fields of the parent class.
  • getFields () to get all of the public (public) field of a class, including the parent class.

Guess you like

Origin www.cnblogs.com/cainiao-chuanqi/p/11332110.html