Java deep understanding of reflection

Source: Internet
Author: User

Java deep understanding of reflection
I. Foundation of reflection

Java classes in java programs belong to the same Class of things. The java Class name that describes such things is Class.
For example, many people use the Person Class in java, and many classes use the Class and Person Class instance objects, such as John and James, to represent specific people, the Class represents the bytecode of each Class in the memory.
When a class is loaded into the memory by the class loader, it will occupy a piece of storage space. The content of this space is the class bytecode. Different classes have different bytecode, therefore, their content in the memory is different. These spaces are represented by one object, which has the same type. This type is Class.
 

Return the bytecode in two ways: 1. This bytecode has been loaded and already exists in the jvm, and can be directly returned. 2. No in jvm. The class loader is used for loading. After loading, the bytecode is cached in jvm, And the bytecode will not need to be loaded later.

There are three methods to obtain the bytecode of a class:

 

1. String. class2.Person p = new Person (); p. getClass (); object. class3.Class. forName (java. lang. String );

Understanding: a total of 9 pre-defined Class objects, 8 Basic Types + void. class

Class Instance Object of the array type, int []. class. isArray (); the byte code of the int array is an array
In short: as long as the types in the source program have their own class instance objects, int [], void

Demo:

 

 

Public static void main (String [] args) throws Exception {String str1 = abc; Class class1 = str1.getClass (); Class class2 = String. class; Class class3 = Class. forName (java. lang. string); System. out. println (class1 = class2); System. out. println (class2 = class3); System. out. println (class1.isPrimitive (); // whether it is the original type, false, it is a class System. out. println (int. class. isPrimitive (); // trueSystem. out. println (int. class = Integer. class); // falseSystem. out. println (int. class = Integer. TYPE); // trueSystem. out. println (int []. class. isArray (); // true}

 

 

2. Understand the concept of reflection

A typical conclusion from a Daniel is that reflection maps various components of Java classes into corresponding Java classes.


A java Class is represented by a Class object. The components of a Class include constructor, method, member variable, and package. The car itself is a Class, its tires and engines are also classified. The java Class provides a series of methods to obtain information such as constructors, methods, and member variables. Such information is the Instance Object of the corresponding Class,Field, Method, Contructor, and Package.
Each member of a class can be represented by an instance object of the corresponding reflection API class.
System. exit (0 );
System. gc ();
System is a class
Exit, gc is also a class
Method method1 stands for exit ()
Method2 indicates gc ()
They all belong to the Method class.

In this way, we can understand the core idea of java: Everything is an object. Everything is an object.

Iii. Application of reflection

1. Constructor
The Constructor class represents a Constructor in a class.


Obtain all Constructor constructors = Class. forName (java. lang. String). getConstructors ();

Get a Constructor constructor = Class. forName (java. lang. String). getConstructor (StringBuffer. class );
It can also be: Constructor constructor = String. class. getConstructor (StringBuffer. class );

When obtaining the instance object, you should note that the instance object type is specified, because the compiler only knows that it is an object, but does not know what type of object String str = (String) constructor. newInstance (new StringBuffer (abc ));

2. member variables

The Field class represents a member variable in a class.

Note that fiedx represents the definition of x rather than the specific x variable. To get the x variable, you must obtain it from the object.

 

Public class Reflection {private int x; public int y; public Reflection (int x, int y) {super (); this. x = x; this. y = y ;}} import java. lang. reflect. field; public class LreanReflect {public static void main (String [] args) throws Exception {Reflection re = new Reflection (3, 4); Field fieldy = re. getClass (). getField (y); // What is fieldy? 4? Wrong. fieldy is not a variable on an object, but a class. Use it to get the value int st = (Integer) fieldy on an object. get (re); System. out. println (st); // x is a private Field fieldx = re. getClass (). getDeclaredField (x); // you can see it, but you cannot use fieldx. setAccessible (true); // brute force reflection, regardless of whether it agrees, I will use st = (Integer) fieldx. get (re); System. out. println (st );}}

 

 

Comprehensive case of member variable reflection

Change B in the String content corresponding to all String member variables in any object to

Import java. lang. reflect. field; public class LreanReflect {public static void main (String [] args) throws Exception {Reflection reflection = new Reflection (3, 4); ChangeStringValue (reflection); System. out. println (reflection);} private static void ChangeStringValue (Object obj) throws Exception {Field [] fields = obj. getClass (). getFields (); for (Field f: fields) {// if (f. getType (). equals (String. class) // because there is only one String bytecode if (f. getType () = String. class) {String str = (String) f. get (obj); // String value = str. replaceAll (B, a); String value = str. replace ('B', 'A'); f. set (obj, value); // update the changed value to Reflection }}} package ReflectLearn; public class Reflection {private int x; public int y; public String str1 = ball; public String str2 = basketball; public String str3 = mail; public Reflection (int x, int y) {super (); this. x = x; this. y = y ;}@ Overridepublic String toString () {return str1 ++ str2 ++: + str3 ;}}

3. Member Methods


(1) Call Method

 

Method method = String. class. getMethod (charAt, int. class); String str1 = abc; System. out. println (method. invoke (str1, 1); // invoke, call // If xxx. if the first parameter of invoke (null, 1) is null, this method must be static because no object is required.

(2) reflection on the member methods that receive array parameters

Write a program that can execute the main method in the class according to the class name provided by the user.

 

 

Import java. lang. reflect. method; public class LreanReflect {public static void main (String [] args) throws Exception {// MyMain. main (new String [] {11,22, 33}); String startingClassName = args [0]; // you need to set the main parameter here, because I don't know which main method to run // run as-> run Configurations-> Arguments (ReflectLearn. myMain) System. out. println (startingClassName); Method mainMethod = Class. forName (startingClassName ). getMethod (main, String []. c Lass); mainMethod. invoke (null, new Object [] {new String [] {11,22, 33}); // package // mainMethod. invoke (null, (Object) new String [] {11,22, 33}); // Why Do I Need To package? The main method accepts a parameter (String Array), and we pass it a string array // an array in JDK1.5 corresponds to a parameter, but in JDK1.4, each element in the array corresponds to a parameter // we pass a String [], that is, an Object array. Once opened, each element is a parameter, it will think that it will receive 3 parameters // so, use the Object array and try another package. In this way, I will give you a package of things. After opening it, it will be an array, in this case, it's okay. // It's official because it needs to be split, so I'll give you a pack in advance} class MyMain {public static void main (String [] args) {for (String s: args) {System. out. println (s );}}}

(3) array reflection

An array is also an Object. Every array of the same element type and dimension is the same class.

 

 

Import java. lang. reflect. array; import java. util. arrays; public class LreanReflect {public static void main (String [] args) throws Exception {int [] arr1 = new int [3]; int [] arr2 = new int [4]; int [] [] arr3 = new int [3] [4]; String [] arr4 = new String [] {, b, c}; System. out. println (arr1.getClass () = arr2.getClass (); System. out. println (arr1.getClass (). getName (); System. out. println (arr1.getClass (). getSuperclass (). getName (); Object obj1 = arr1; // Object [] obj2 = arr2; otherwise, Object [] obj3 = arr3; Object obj4 = arr4; Object [] obj5 = arr4; system. out. println (Arrays. asList (arr1); System. out. println (Arrays. asList (arr4); // The string can be printElement (arr1);} private static void printElement (Object arr1) {Class c = arr1.getClass (); if (c. isArray () {int len = Array. getLength (arr1); for (int I = 0; I
 
  Extension: About hashCode when an object is stored in a HashSet set, you cannot modify the fields involved in calculating the hash value of this object. Otherwise, the modified hash value of the object is different from the hash value originally stored in the HasgSet set, which leads to the use of the contains of the current collection object to check the modified object, A retrieval failure occurs. As a result, the pre-modified object cannot be deleted from the HashSet set, causing memory leakage.
  

 

 

Public class Reflection {private int x; public int y; @ Overridepublic int hashCode () {final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result;} @ Overridepublic boolean equals (Object obj) {if (this = obj) return true; if (obj = null) return false; if (getClass ()! = Obj. getClass () return false; Reflection other = (Reflection) obj; if (x! = Other. x) return false; if (y! = Other. y) return false; return true;} public Reflection (int x, int y) {super (); this. x = x; this. y = y ;}} public class ReflectTest2 {public static void main (String [] args) {Collection conCollection = new HashSet (); reflection [] rs = new Reflection [] {new Reflection (3, 3), new Reflection (4, 4), new Reflection (3, 3)}; for (Reflection r: rs) conCollection. add (r); // rs [0]. y = 1; System. out. println (conCollection. contains (rs [0]); boolean B = conCollection. remove (rs [0]); System. out. println (B); System. out. println (conCollection. size () ;}} truetrue1 open the comment falsefalse2

Therefore, if we save an object to the set, modify the object, and delete the object, the object is not deleted. As a result, the memory is leaked. So do not save the objects in the set.
Modified

Iv. Concepts of frameworks and principles of developing frameworks using reflection technology

Function of reflection-> Implementation Framework
Simulate a super-small frame

 

 

Config. propertiesclassName = java. util. arrayListpublic class Reflection {private int x; public int y; public Reflection (int x, int y) {super (); this. x = x; this. y = y ;}} public class ReflectTest2 {public static void main (String [] args) throws Exception {InputStream in = new FileInputStream (D:/JavaSourue/config. properties); Properties pro = new Properties (); // What kind of pro is obtained from the configuration file. load (in); in. close (); String className = pro. getProperty (className); Collection conCollection = (Collection) Class. forName (className ). newInstance (); Reflection [] rs = new Reflection [] {new Reflection (3, 3), new Reflection (4, 4), new Reflection (3, 3 )}; for (Reflection r: rs) conCollection. add (r); System. out. println (conCollection. size ());}}

Framework:
A rough room is a framework, and the user installs doors, windows, etc. The user uses a framework, and the doors and windows are inserted into the framework.
The difference between the framework and the tool class is that the tool class is called by the user, and the class provided by the Framework Call User

The framework solves the following problems:
When a real estate agent builds a house (as a framework), the user may not buy a house and naturally will not think of decoration. How can the framework call the classes written by the user in the future?

 


When writing a framework, there is nowhere to know what class to call in the future, so the new object cannot be created. Therefore, reflection must be used to solve this problem.

 

Related Article

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.