Java reflection mechanism, it can be said that we use a lot of common development, although as a developer, we do not feel, it is because the framework of the designer, has been packaged for us, we just need to call it. Before also used to reflect, including oneself also wrote, also learned, but I feel are relatively shallow, today has time, I feel that it is necessary to slowly in-depth understanding.
We refer to the ability to analyze classes as reflection (reflective). The reflection mechanism function and its powerful, simply say a few reflection of the use:
1. Ability to analyze classes in operation;
2. View objects in the run, such as writing a generic ToString method;
3. Implement the common array operation code;
4. Use method object;
In fact, the use of reflection is very simple, we just remember that the first step in the use of reflection is to get class, then this class is what, we have to pay attention to, this class and class is different, class is a type, a keyword, he is the basic elements of Java, We all know that ordinary classes in Java are decorated with class, and enumerations are decorated with enum and so on. And our class says:
During a program run, the Java system maintains a type identity known as the runtime for all objects. This information tracks the classes that each object belongs to. We keep all the information about this class in class. As long as we get the class, we can get the result we want according to its specific method;
Without a deeper understanding of class, we just need to remember that class is like the key to the treasure trove, with the classes, objects, methods, and constructors we need, but without this key, everything is useless. So we have to construct the class first;
Take a look at three ways to construct class;
1.class.forname ("Class name string") (Note: Class name string must be full name, package name + class name)
2. Class name.
3. Instance object. GetClass ()
First, create a simple person class;
<pre name= "code" class= "Java" >public class person implements serializable{ private int id; public String name; protected String address; int age; static{ System.out.println ("Static initialization Block"); } { System.out.println ("Initialize Fast"); }
Omit Get,set, constructor and other basic methods;
public static void Main (string[] args) {try {class c1=class.forname ("Com.cn.vo.Person");//By class name to get class, The package name is also part of the class name C2=person.class; Get Classperson p=new person () through class object; Class C3=p.getclass (); Get ClassSystem.out.println (C1) by object reference; System.out.println (C2); System.out.println (C3); System.out.println (C1==C3);} catch (ClassNotFoundException e) {e.printstacktrace ();}}
The simplest way to get class from a class object here is to note that a class object actually represents a type, and that type is not necessarily a class, such as an int is not a class, but Int.class is an object of class type.
However, whichever method you use, you can only get one class at a time, because our static initialization block executes only once, proving that our class has only been loaded once.
So, the process of generating a class object is actually the same:
when we write a new Java class, the JVM will compile it into a class object, stored in a. class file of the same name. At run time, when the object of this class needs to be generated, the JVM checks to see if the class is already loaded in memory. If it is not loaded, the. class file is loaded into memory. If loaded, the instance object is generated according to the class file. As a result, we can conclude that a Java class has only one class.
this is mainly because of the ClassLoader, the ClassLoader uses the parental delegation mechanism, a custom ClassLoader before loading a class, it will first delegate its father ClassLoader to load, only if the Father ClassLoader unable to load successfully, will be loaded by themselves; Take a look at the source code:
Protected synchronized Class loadclass (String name, Boolean resolve) throws ClassNotFoundException { // First check whether the class specified by the name is loaded with class C = findloadedclass (name); if (c = = null) { try { if (parent! = NULL) { ////If Parent is not NULL, call the parent's loadclass to load = Parent.loadclass (name, false); } else { //parent is null, then call Bootstrapclassloader to load c = findBootstrapClass0 (name); } } catch ( ClassNotFoundException e) { //If it still fails to load successfully, call its own findclass to load c = findclass (name);} } if (resolve) { resolveclass (c); } return c; }
Well, the final conclusion is that no matter what method we pass, we just need to get a class is enough, it means that the key to open the Treasury is only one, no matter how to get this is not the most important, the key is to open the door of the Treasury;
Now that we have the class, we can use it to get a lot of things.
Here we use the Reflection class,reflect provides the API method to print all the information of a class;
Briefly describe the main classes of the API
Field class: Represents a member variable of a class (a member variable is also called a property of a class). method Class: Methods that represent classes. Constructor class: Represents the construction method of a class. Array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array.
Here are a few small examples to flexibly use the Java reflection mechanism.
Print out the complete information for a class; The following method prints out the class's package name, class name, method name, and all domain names;
try {String s= "Com.cn.vo.Person"; Class C1=class.forname (s); Get Classstringbuffer sb=new stringbuffer ("Package") by class name; Constructs the package name keyword Sb.append (c1.getpackage (). GetName () + ";" + "\ n"); Get the package name Sb.append (modifier.tostring (C1.getmodifiers ()) + "class" +c1.getsimplename () + "{" + "\ n");//Get the class modifier and class name field[] File=c1.getdeclaredfields (); Get all properties for (Field f:file) {sb.append (modifier.tostring (F.getmodifiers ()) + ""); Get modifier sb.append (F.gettype (). Getsimplename () + ""); Get the variable type sb.append (F.getname () + ";"); Get the variable name sb.append ("\ n"); }method[] Methods=c1.getdeclaredmethods (); Get all the methods for (method M:methods) {Class rettype=m.getreturntype ();//Get the method type Sb.append (Modifier.tostring ( M.getmodifiers ()) + ""); Get modifier sb.append (rettype+ ""); Sb.append (M.getname () + ";"); Get the method name Sb.append ("\ n");} Sb.append ("}");} catch (Exception e) {e.printstacktrace ();}
Access sets the class without the Get,set method ;
We usually have its get and set method in the development of a javabean, but if there is no get, set method, then how to get its value and change its value, we can use Java Reflection technology;
try {person P=new person ("Zhang San", "Xiangyang, Hubei", 23); Class C2=p.getclass (); Field F=c2.getdeclaredfield ("address"); Get the domain name F.setaccessible (true); Set to True to also access the private class; Object St=f.get (P);//Get the domain name value f.set (p, "Wuhan"); Reset value System.out.println (p);} catch (Exception e) {e.printstacktrace ();}
Here is a method called the Setaccessible method, which is a public superclass of the Field,method and constructor classes, which is provided by debugging, persistent storage, and similar mechanisms. We must set to true when we want to access the private decorated class.
Design a generic tostring method;
public static String toString (Object obj) {if (obj==null) return null; Class C1=obj.getclass (); if (C1==string.class) return (String) obj; If the string object is passed in, the result is printed directly stringbuffer st=new stringbuffer (); try {if (C1.isarray ()) {//Array object St.append ( C1.getcomponenttype () + "[]{"); Type for (int i=0;i<array.getlength (obj); i++) {//traversal array if (i>0) st.append (","); Object val=array.get (obj, i);// Loop value St.append (val);} Return St.append ("}"). toString ();} The parent class of each class is Object, where it is not printed, while (C1.getsuperclass ()!=null&&!c1.getsimplename (). Equals ("Object")) {St.append (C1.getname () + "["); Class name field[] Fields=c1.getdeclaredfields (); Get all the Attributes Accessibleobject.setaccessible (fields, true); Set private properties for the access permission for (Field f:fields) {if (!st.tostring (). EndsWith (")") St.append (","); St.append (F.getname () + "=");//printing, , get the property name Object Val=f.get (obj); Get the attribute value St.append (val);} St.append ("]"); C1=c1.getsuperclass (); Get the parent class up recursion;}} catch (Exception e) {e.printstacktrace ();} return st.tostring ();}Although the reflection mechanism is very powerful, it allows us to write programs that are more versatile, but we do not use reflection when we develop modules on a daily basis, because reflection is weaker and less prone to error. Let's go to this place today and explore the connection between spring,struts and reflection next time.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Explore the Java reflection mechanism