Reflection and Regular Expressions

Source: Internet
Author: User

Reflection technology:In fact, it is 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.

 

Benefits of reflection:This greatly enhances program scalability.

 

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) hasStatic 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: Methods in the class used,StaticFornameMethod.

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)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 constructor in the class is used.Newinstance ()Method.

2. Call a constructor with parameters: first obtain the constructor object of the specified parameter list, and then use the constructor'sObject newinstance (actual parameter)Initialize the 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 =NewPerson ("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 );

}

 

Regular Expression:★★★☆,It is actually a rule used to operate strings.

Benefits:Regular Expressions make it easier to perform complex operations on strings.

Features:The code for string operations is represented by some symbols. With the specified symbol, you can call the underlying code to operate the string. The appearance of symbols simplifies code writing.

Disadvantages:The appearance of symbols simplifies writing, but reduces readability.

In fact, more problems are solved by using regular expressions.

 

GROUP:It is marked with parentheses. Each parentheses is a group with an automatic number starting from 1.

If you use a group, the corresponding number is the content of the group. Do not forget to add \ To the array \\.

(Aaa (wwww (CCC) (eee) tips, starting from the left parenthesis. There are several left parentheses.

 

Common Operations:

1. Matching: Actually, the matches method in the string class is used.

String Reg = "[1-9] [0-9] {4, 14 }";

Boolean B = QQ.Matches(REG); // associate the regular expression with the string to match the string.

2. Cut: The split method in the string class is used.

3. Replace: replaceall () in the string class ();

4. obtain:

1), first compile the regular expression into a regular object. The static method compile (RegEx) in pattern is used );

2) Get the matcher object through the pattern object.

Pattern is used to describe a regular expression and can be parsed.

The rule operation string needs to be re-encapsulated into the matcher object.

Then, use the matcher object method to operate the string.

How can I obtain a matcher object?

Use the matcher method in the pattern object. This method can be associated with strings based on regular rules. And returns the matching object.

3) use the method in the matcher object to perform various regular operations on the string.

Reflection and Regular Expressions

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.