Java reflection mechanism concepts
“When a program is running, it is allowed to change the structure of the program or the type of a variable. These languages are called dynamic languages.” For example, Python and Ruby are dynamic languages. Obviously C++, Java, and C# are not dynamic languages, but Java has a very prominent dynamic correlation mechanism: Reflection.
The JAVA reflection mechanism allows you to know all the properties and methods of any class in the running state. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language.
Such as:
/ * *
* Entry-level example: Get the package name by object. The name of the class
* @author Administrator
* /
public class Simple {
public static void main(String[] args) {
Simple s=new Simple();
System.out.println(s.getClass().getName());
}
}
Copy the code
“Java reflection mechanism, which can achieve the following functions:“
(1) Determine the class of any object at runtime;
② Construct an object of any class at runtime;
③ Determine the member variables and methods of any class at run time;
(4) call the method of any object at run time;
⑤ Generate dynamic proxy.
“The relevant API is“
Get the source Class
Open permissions:
add.setAccessible(true);
Objects of all classes are actually instances of Class. This Class instance can be thought of as a template for the Class, which contains the structure information of the Class, similar to a drawing. In our daily life, we need to create a product, such as a copycat iPhone, how to do?
“This can be done in three ways:“
(1) Buy an iPhone, disassemble, start copying;
(2) Visit iPhone factory, get iPhone grinding tools, start copying;
⑶ went to the United States to steal iPhone drawings, began to copy, the last one of the most violent, the most cool.
Serialization: Implements the Serializable interface
deserialization
Clone: implement cloneable interface, rewrite clone () method, change permission to public
The New reflection
Similarly, there are three ways to obtain a class object:
(1) Class. Class.forname (” package name. Class name “)// This form is generally used
(2) class. The class
(3) object. GetClass ()
“The following is an example:“
public class Source {
public static void main(String[] args) {
// The first method is object.class
Source s=new Source();
Class<? >c1=s.getClass();
// Second way: class.class
Class<? >c2=Source.class;
// Third method (recommended) : class.forname ()
Class<? >c3=null;
try {
c3=Class.forName("com.shsxt.ref.simple.Source");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(c1.getName());
System.out.println(c2.getName());
System.out.println(c3.getName());
}
}
Copy the code
With the class object, we have everything. That’s where the reflection starts. The next step is “paoding”.
“PS: access to learning resources technical dry products: lezijie007 (code 1024)“