reflection mechanism
In an existing java program, with the change of requirements, if we need to expand or improve the program, it is generally not a good thing to modify the source code.
And if we can redefine new classes and expand on the basis of the original program, then we don't have to worry about modifying complex source code. Change
In other words, can you define a new class without changing the source code of the original class, and then extend it on the basis of preserving the original function?
Fortunately, java 's reflection mechanism solves this problem very well. The newly defined class is compiled into a bytecode file to form a class file (byte
code file). The java reflection technology opens the class file, dissects it, and obtains the internal data structure. Since the application cannot make changes, but the program runs
The internal data of the class file can be specified, and the internal data of the class file can be obtained and processed. For the application, there is no need to know that we define new
The extended class only needs to know the bytecode of the new class and give it to it, and it will use reflection technology to deal with it. The JAVA reflection mechanism is in the running state, for any class,
can know all the properties and methods of this class; for any object, can call any of its properties and methods; this dynamic acquisition of information and
The function of dynamically calling the method of an object is called the reflection mechanism of the java language. It should be noted that in order to dissect a class, you must first obtain the class file object of the class.
The anatomy uses the methods in the java.lang.Class class. For the methods of this class, please refer to the official JAVA API documentation. Even we can extend the program,
Can we "scratch" and mess around with our own defined classes? In order to use the newly extended class more safely, the reflection mechanism performs a special kind of special
Interface constraints. So it is safe to use reflection mechanism.
In any object-oriented programming language, objects must be real things, and classes are abstract descriptions of the characteristics of things. java.lang.Class in java
A class is a class used to describe objects of a class. Instances of the Class class represent classes and interfaces in a running java application. Any class can be obtained using the reflection mechanism
All properties and methods of . So how can I get the method of the Class file object? The following will introduce the three methods to obtain the Class file object. for better shape
Following the description of the image, we created a Good class.
public class Goods { public String goodsName; //Commodity name public double price; //price /*static { System.out.println("Static code block"); }*/ // no-argument constructor public Goods() { } // parameterized constructor public Goods(String goodsName,double price) { this.goodsName = goodsName; this.price = price; } public void goods() { System.out.println("Product Overview"); } public void info(String gname, double gprice) { System.out.println(gname+"The price is: "+gprice); } }
Method 1: Object acquisition
Call the getClass() method directly with an object of a certain class, which returns a Class object. If we print the return value of the Class object at this point,
You will find that what is printed out is actually the full name of a class. for example:
Goods good = new Goods(); Class c = good.getClass(); System.out.println(c); //full name of output class
Method 2: Get the class name
For each type (including basic types and reference types), the JVM will assign a static attribute to the type, and the name of the attribute is called class . we wrote it ourselves
This property cannot be seen in the code, but when we call it with the class name, this property does exist. I believe we have all encountered in static synchronization locks
Seen it, all types have class attribute, such as double.class and so on.
Class c = Goods.class; System.out.println(c); //full name of output class
Method 3: Obtaining the static method of the Class class
Use the static method forName(String className) to get it. The advantage of using this method is that the class name can use a string. Since it is a string, it is used in
It will increase its flexibility when used. Note in particular that className must use the full name of the class. When using this method, the local method in which it is located must throw an exception,
If you are too troublesome, you can throw Exception directly .
Class c = Class.forName("com.gzhxtc.win.Goods"); System.out.println(c); //full name of output class
Is the class file object unique when creating the class file for the class in the class loader ? To prove this problem, we separate
Created two objects, and then compared the reference and internal use of the two objects to be the same, and the results of the experiment told us that this is indeed the same object.
Class c1 = Class.forName("com.gzhxtc.win.Goods"); Class c2 = Class.forName("com.gzhxtc.win.Goods"); / / Determine whether the reference of the two objects wants to wait, the result is: true System.out.println(c1 == c2); / / Determine whether the content of the two objects want to wait, the result is: true System.out.println(c1.equals(c2));
The three methods for obtaining Class file objects were introduced earlier . These three methods have their own merits, but the third method is the most used - the Class class.
Get static method. This method makes the program more flexible due to the transfer of a string. Now with these three ways to get the Class file object, I
Next, we will cut to the topic, how to obtain the member properties and methods in the class in the program? The following will introduce the acquisition of various variables in the class.
First, the reflection acquisition method
1. No parameter constructor
/* * Get all the public-decorated constructors in the class * There are many methods for us to use in the Class class, generally the getConstructors() method is more commonly used, * This method can get all public modified constructors in the class file object. Its return value is * Constructor[] array, which accepts multiple constructors. Constructor is the class that describes the construction method. */ Class c = Class.forName("com.gzhxtc.win.Goods"); Constructor[] cons = c.getConstructors(); for (Constructor constructor : cons) { System.out.println(constructor); } // Output the full name of the constructor: //public com.gzhxtc.win.Goods() //public com.gzhxtc.win.Goods(java.lang.String,java.lang.String) /* * Get the specified public-decorated constructor */ Class c = Class.forName("com.gzhxtc.win.Goods"); //newInstance() method here because it is a parameterless constructor, so no parameters are passed Object obj = c.newInstance(); //If you want the obj object to be able to use the methods in the class, you must cast the type Goods good = (Goods)obj; //Then good can call the method in Goods good.goods(); System.out.println();//Output: product overview
2. There are parameter constructors
/* * Get the public-decorated constructor with parameters, the class file object that needs to pass parameters */ Class c = Class.forName("com.gzhxtc.win.Goods"); //Get the parameterized constructor Constructor constructor = c.getConstructor(String.class, double.class); Object obj = constructor.newInstance("Heat Rod",99.99); Goods good = (Goods)obj; System.out.println(good.goodsName); //Output: electric heating rod System.out.println(good.price); //Output: 99.99
Second, reflection to obtain the member variables of the class
/* * Use the getFields() method to get all public member variables in the class file * When importing the package, it is in the lang package, don't make a mistake */ Class c = Class.forName("com.gzhxtc.win.Goods"); Field[] fileds = c.getFields(); for (Field field : fileds) { System.out.println(field); } //Get the specified public member variable Field field = c.getField("goodsName"); Object obj = c.newInstance(); //run //Modify member variables, the parameters must have the support of the object and the modified value field.set(obj, "rice cooker"); Goods good = (Goods)obj; System.out.println(good.goodsName); //Output: rice cooker
Three, reflection to get member method
1. public member method with no parameters
/* * All public methods (including inherited) in the class file obtained with getMethods() */ Class c =Class.forName("com.gzhxtc.win.Goods"); Method[] methods = c.getMethods(); for (Method method : methods) { System.out.println(method); }
2. Member methods with public parameters
/* * Get the specified member method */ Class c =Class.forName("com.gzhxtc.win.Goods"); Object obj = c.newInstance(); //run Method method = c.getMethod("info",String.class,double.class); //Call the invoke of the Method class method.invoke(obj, "refrigerator", 2999.0); //Output: The price of the refrigerator is: 2999.0
The above is the basis of reflection technology. For more methods of reflection technology, please refer to the official documentation of Java API 1.8.