java reflection

java reflection

Java reflection: Dynamically load the specified class, get all the content (attributes, behavior characteristics) of the class, and encapsulate the content in the word decoding file into objects, which is convenient for manipulating these members. Simply speaking - java reflection technology is to a class to parse.

Reflection steps:
1. Obtaining the Class object is to obtain the bytecode file object with the specified name.

2. Instantiate the object to obtain the properties, methods or constructors of the class.

3. Access properties, call methods, and call constructors to create objects.

The method of reflection:
1: Obtained through the method getClass that each object has. Disadvantages: The object of this class must be created before the getClass method can be called.

2: Each data type (basic data type and reference data type) has a static attribute class. Disadvantages: The class must be specified first.

     The first two methods are not conducive to the extension of the program, because they all need to use specific classes in the program to complete.

3: The method in the Class class used, the static forName method.

     Specify the class name to obtain the bytecode file object of the class. This method is the most scalable. Just pass in the string of the class name.
// 1. Obtain the file object for the class according to the given class name. Class loading

String classname = "cn.itcast.reflect.Person";// From the configuration file
Class clazz = Class.forName(classname);// This object represents Person.class
// 2. If you get the object, I don't know if it is What type is used to get the type of the

object Object obj = new Person();
Class clazz1 = obj.getClass();// Get the specific type of the object
// 3. If you explicitly get the Class object of a class, it is mainly used for pass parameters
Class clazz2 = Person.class;    

usage of reflection:

1) To obtain the various components of the java class, you first need to obtain the Class object of the class, and three ways to obtain the Class object:

    Class.forName(classname) is used for class loading
    obj.getClass() is used to obtain the type
    class name of the object. class is used to obtain the specified type, pass the parameter


2), the member method of the reflection class:

    Class clazz = Person.class;
    Method method = clazz.getMethod(methodName, new Class[]{paramClazz1, paramClazz2});
    method.invoke();

3) Constructor of reflection class:
    Constructor con = clazz.getConstructor(new Class[]{paramClazz1, paramClazz2,...})
    con.newInstance (params...)

4), attributes of the reflection class:
    Field field = clazz.getField(fieldName);
    field.setAccessible(true);
    field.setObject(value);


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324678077&siteId=291194637