Dark Horse programmer: Reflection

Source: Internet
Author: User
-------
Android training and Java training. We look forward to communicating with you!
----------


Reflection technology: it is actually to dynamically load a specified class and obtain all the content in the class. In addition, the bytecode file is encapsulated into an object and the content in the bytecode file is encapsulated into an object, which facilitates the operation of these members. To put it simply, reflection technology can dissect a class.

The advantage of reflection: it greatly enhances the scalability of the program.

Basic Steps for reflection:

1. Get the class object, that is, get the bytecode file object of the specified name.

2. instantiate the object to obtain the attributes, methods, or constructor of the class.

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

There are three methods to obtain this class object:

1: Get it through the getclass method that each object has. Disadvantage: You must create this class object before calling the getclass method.

2: each data type (basic data type and referenced data type) has a static attribute class. Disadvantages: You must specify this class first.

The first two methods are not conducive to program expansion, because they both need to be completed using specific classes in the program.

3: The method in the class used, the static forname method.

If you specify a class name, you can obtain the class bytecode file object. This method has the strongest scalability. You only need to pass in the class name string.

// 1. Obtain the class used for loading based on the given class name

String classname = "cn. itcast. Reflect. Person"; // from the configuration file

Class clazz = Class. forname (classname); // This object represents person. Class

// 2. If an object is obtained, you do not know what type is used to obtain the object type.

Object OBJ = new person ();

Class clazz1 = obj. getclass (); // obtain the object type

// 3. If the class object of a class is explicitly obtained, it is mainly used to pass parameters.

Class clazz2 = person. Class;

Reflection usage:

1) to obtain the components of a Java class, you must first obtain the Class Object of the class and obtain the Class Object in three ways:

Class. forname (classname) is used for class loading.

OBJ. getclass () is used to obtain the object type.

Class Name. Class is used to obtain the specified type, and parameter passing is used

2) Reflection class member methods:

Class clazz = person. Class;

Method method = clazz. getmethod (methodname, new class [] {paramclazz1, paramclazz2 });

Method. Invoke ();

3) constructor of the 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 );

After obtaining the bytecode object, you must create the object of the specified class:

Two ways to create an object (in fact, the initialization method when the object is instantiated ):

1. Call the constructor with null parameters: the newinstance () method in the class is used.

2. Call a constructor with parameters: first obtain the constructor object of the specified parameter list, and then initialize the object through newinstance (actual parameter) of the constructor object.

To sum up, the second method must first specify the parameter type of the specific constructor, which is not easy to expand. Therefore, the reflected class usually provides a public constructor with null parameters.

------------------------------------------------------

// How to generate an instance object that obtains the bytecode file object.

Class clazz = Class. forname ("cn. itcast. Bean. person"); // class loading

// Directly obtain the specified type

Clazz = person. Class;

// Obtain the type based on the object

Object OBJ = new person ("zhangsan", 19 );

Clazz = obj. getclass ();

Object OBJ = clazz. newinstance (); // The method call of the instantiated object is an empty parameter constructor in the specified class, which initializes the created object. When no parameter constructor exists in the specified class, how does one create this class object? See method_2 ();

Public static void method_2 () throws exception {

Class clazz = Class. forname ("cn. itcast. Bean. person ");

// Since there is no constructor with null parameters in the class, it is only used to obtain the constructor of the specified parameter for instantiation.

// Obtain a constructor with parameters.

Constructor = clazz. getconstructor (string. Class, Int. Class );

// To initialize the object, use the constructor method newinstance ();

Object OBJ = constructor. newinstance ("zhagnsan", 30 );

// Obtain all constructors.

Constructor [] constructors = clazz. getconstructors (); // only contains public

Constructors = clazz. getdeclaredconstructors (); // contains private

For (constructor con: constructors ){

System. Out. println (CON );

}

}

------------------------------------------------------

Reflection:

// Obtain all methods in the class.

Public static void method_1 () throws exception {

Class clazz = Class. forname ("cn. itcast. Bean. person ");

Method [] Methods = clazz. getmethods (); // obtain the public methods in the class and the public methods in the parent class.

Methods = clazz. getdeclaredmethods (); // obtain methods in this class, including private methods.

For (method: Methods ){

System. Out. println (method );

}

}

// Obtain the specified method;

Public static void method_2 () throws exception {

Class clazz = Class. forname ("cn. itcast. Bean. person ");

// Obtain the method of the specified name.

Method method = clazz. getmethod ("show", Int. Class, String. Class );

// To run the specified method, the method object is the clearest. To run the method, call the invoke method of the method object, however, to run a method, you must specify the object and actual parameters.

Object OBJ = clazz. newinstance ();

Method. Invoke (OBJ, 39, "Hehehe"); // execute a method

}

// You want to run a private method.

Public static void method_3 () throws exception {

Class clazz = Class. forname ("cn. itcast. Bean. person ");

// Obtain the private method. Getdeclearmethod () must be used ();

Method method = clazz. getdeclaredmethod ("method", null );

// Private methods cannot be accessed directly because of insufficient permissions. Access is not required. You can use brute force.

Method. setaccessible (true); // it is rarely used, because private is hidden, so try not to access it.

}

// Static reflection method.

Public static void method_4 () throws exception {

Class clazz = Class. forname ("cn. itcast. Bean. person ");

Method method = clazz. getmethod ("function", null );

Method. Invoke (null, null );

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.