Dark Horse programmer-java basics-reflection, dark horse programmer java

Source: Internet
Author: User

Dark Horse programmer-java basics-reflection, dark horse programmer java
Zookeeper

Dark Horse programmers -- java basics -- Reflection

------ Java training, Android training, iOS training, and. Net training. We look forward to communicating with you! -------

Reflection

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.

Reflection maps various components in the Java class into corresponding java classes.

To put it simply:Reflection technology can dissect a class.

The cornerstone of reflection --> Class

1. Classes in java are used to describe the commonalities of a class of things. They have any attributes and have no attributes. What is the value of this attribute, it is determined by the instance object of this class. Different instance objects have different attribute values. All classes in java are also a kind of things. They all share their commonalities, including the packages, class names, attribute access permissions, fields, methods, and other information. We extract the abstract content used to describe the common content of the Class, which leads to a unique Class. This class is the cornerstone of reflection. It is used to represent the class stage of objects in java, the Class Object encapsulates the member variables, member methods, constructor methods, Class names, and package names defined in a java Class.

Person p1 = new Person ("zhangsan ");

Person p2 = new Person ("lisi ");

2. The Class represents the Java Class. What are the corresponding instance objects?

It corresponds to the bytecode of each class in the memory, such as The Byte Code of the Person class and the byte code of the ArrayList class.

A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, therefore, their content in the memory is different. The space can be represented by objects respectively. These objects obviously have the same type, And this type is Class.


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;

 Nine predefined classes:

1) It includes eight basic types (byte, short, int, long, float, double, char, and boolean) of bytecode object and void. class with the return value of void type.

2) Integer. TYPE is a constant of the Integer class. It represents the bytecode of the basic TYPE encapsulated by this packaging TYPE, so it is equal to int. class. The bytecode of the basic data TYPE can be expressed by the TYPE constant in the corresponding packaging class.

All types in the source program have their own Class instance objects, such as int []. class. The Class instance object of the array type. You can use the Class. isArray () method to determine whether the object is of the array type.

Methods in Class

Static Class forName (String className)

Returns the Class object associated with the Class or interface of the given string name.

Class getClass ()

The returned Class is the Class when the Object is running, that is, the Class Object is the bytecode Object.

Constructor getConstructor ()

Returns the Constructor object, which reflects the specified public Constructor of the Class represented by this Class object.

Field getField (String name)

Returns a Field object, which indicates the specified public member Field of the Class or interface that this Class object represents.

Field [] getFields ()

Returns an array containing some Field objects, representing the Member fields in the class.

Method getMethod (String name, Class... ParameterTypes)

Returns a Method object, which indicates the specified public member Method of the Class represented by this Class object.

Method [] getMehtods ()

Returns an array containing some Method objects, which is a common member Method in the class.

String getName ()

Returns the object name represented by this Class object in String format.

String getSuperclass ()

Returns the name of the superclass of the Class represented by this Class.

Boolean isArray ()

Determines whether this Class object represents an array

Boolean isPrimitive ()

Checks whether the specified Class object is a basic type.

T newInstance ()

Creates a new instance of the Class represented by this Class object.

Constructor class

If the specified class does not contain a constructor with null parameters, or the class object to be created must be initialized using the specified constructor. What should we do? In this case, the newInstance method in the Class cannot be used. Since object initialization is required through the specified constructor. You must first obtain the Constructor. Constructor represents the Constructor of a class.

2. Obtain the constructor:

1) obtain all constructor methods of the class. For example, obtain all constructor methods of the Person class in the above example.

Constructor [] cons = Class. forName ("cn. itheima. Person"). getConstructors ();

2) Obtain a constructor:

Constructor con = Person. class. getConstructor (String. class, int. class );

Create an instance object:

1. Common method: String str = new String (new StringBuffer ("abc "));

Reflection Method:

Constructor constructor = Class. forName ("java. lang. String"). getConstructor (StringBuffer. class );

String str = (String) constructor. newInstance (new StringBuffer ("abc "));

2. There is a convenient method for creating instance objects in the Class object:

String obj = (String) Class. forName ("java. lang. String"). newInstance ();

In this method, the default constructor is obtained first, and then the instance object is created using this constructor. (Javabean requires a default constructor)

How is the code written in this method written? The cache mechanism is used to save the instance objects of the default constructor.

Filed type

The Field class represents a member variable in a class.

Method:

Field getField (String s); // only public in public and parent classes can be obtained

Field getDeclaredField (String s); // obtain any member variables in the class, including private

SetAccessible (ture );

// If it is a private field, you must first cancel the permission check for this private field. Also known as brute-force access.

Set (Object obj, Object value); // set the Field represented by this Field Object on the specified Object variable to the specified new value.

Object get (Object obj); // returns the value of the Field on the specified Object.

class ReflectPoint {      private int x;      public int y;      public ReflectPoint(int x, int y) {          super();          this.x = x;          this.y = y;      }  }  

Reflection field:

// Reflection of Member Fields

ReflectPoint pt1 = new ReflectPoint (3, 5 );

Field filedY = pt1.getClass (). getField ("y ");

System. out. println (filedY );

System. out. println (filedY. get (pt1 ));

// Brute force reflection of private fields

Field fieldX = pt1.getClass (). getDeclaredField ("x"); // you can obtain a private Field but cannot use it.

System. out. println (fieldX );

FieldX. setAccessible (true); // use it forcibly after brute force reflection

System. out. println (fieldX. get (pt1 ));

Exercise: Change "B" to "a" in the String content corresponding to all String-type member variables in any object ".

The code for implementing this function is as follows:

public class ReflectPoint {String x;String y;public String str1 = "basketball";public String str2 = "ball";public ReflectPoint(String x, String y) {super();this.x = x;this.y = y;}@Overridepublic String toString() {return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + "]";}}public class Test {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubReflectPoint rp = new ReflectPoint(String.valueOf(3), String.valueOf(4));Field[] fields = ReflectPoint.class.getFields();for (Field field : fields) {if (field.getType() == String.class) {String str = (String) field.get(rp);System.out.println(str.replace("b", "a"));}}}}

Method class

The Method class represents a member Method in a class.

1. You should learn the APIs in Reflection Through thinking and reasoning. For example, the Class. getMethod method is used to obtain a method. What parameters should this method accept? Obviously, a method name is required, and a method with the same name has multiple reload forms. How can I identify which method in the method series to be reloaded? Based on the number and type of parameters, for example, The args parameter in Class. getMethod (name, Class... args) represents a list of the types of parameters of the method to be obtained.

Again, what is the parameter type used for representation? Use Class object!

Method

Method [] getMethods (); // only obtain methods in the public and parent classes.

Method [] getDeclaredMethods (); // obtain private information contained in this class.

Method getMethod ("Method name", parameter. class (null can be written if it is a null parameter ));


Obtain a method in the class:

Method charAt = Class. forName ("java. lang. String"). getMethod ("charAt", int. class );

Call method:

Common method: System. out. println (str. charAt (1 ));

Reflection Method: System. out. println (charAt. invoke (str, 1 ));

Array reflection

1. Arrays with the same dimension and element types belong to the same type, that is, they share the same Class instance object.

2. The parent Class returned by the getSupperClass () method of the Class instance Object of the array is the Class corresponding to the Object Class.

3. Basic Types of one-dimensional arrays can be used as objects, but not as objects;

Non-basic types of one-dimensional arrays can be used either as the Object type or as the Object.

Int [] a1 = new int [3];

Int [] a2 = new int [4];

Int [] [] a3 = new int [3] [4];

String [] a4 = new String [3];

Integer [] a5 = new Integer [3];

Object [] aObj3 = a5; // yes. Non-basic types of one-dimensional arrays can be used as Object [] types.

// Object [] aObj4 = a1; // No. Basic Types of one-dimensional arrays cannot be used as Object;

Object aObj1 = a1; // yes. Basic Types of one-dimensional arrays can be used as Object types.

Object aObj2 = a4; // yes. Non-basic types of one-dimensional arrays can be used as objects;

System. out. println (a1.getClass () = a2.getClass (); // true

Framework

A Method for calling Java classes through reflection.

For example, users who build real estate houses, doors and windows, air conditioners, and so on are installed on their own. The house is a framework. users need to use this framework and install the doors and windows in the framework provided by real estate agents.

The difference between the framework and the tool class: the tool class is called by the user class, and the framework is the class provided by the user.

Core issues to be solved by frame machines

When we write a framework (house building process), the called class (Installed doors and windows) has not yet appeared, so the framework cannot know the name of the class to be called, therefore, you cannot directly create an instance object of a class in a program, but instead use reflection.

Steps for a simple framework program:

1) Right-click the project File and name a configuration File, such as config. properties, and write the configuration information. For example, key-value pairs: className = java. util. ArrayList, the configuration key on the right of the equal sign, and the value on the right.

2) code implementation: load the file:

① Read the file into the read stream and write the absolute path of the configuration file.

For example, InputStream is = new FileInputStream ("configuration file ");

② Use the load () method of the Properties class to store the data in the stream to the set.

③ Close the stream: close reading the stream because the data in the stream has been loaded into the memory.

3) Get the className through the getProperty () method, that is, the configured value, that is, a class name.

4) use reflection to create the newInstance () object ().

5) execute the main program function

 






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.