Detailed explanation of java reflection mechanism

For ordinary developers, it is rarely necessary to directly use java reflection mechanism to complete function development, but reflection is the core of many frameworks, such as spring and mybatis. Although the reflection is small, it has great energy.

This article mainly introduces the concepts related to reflection and the use of API. The application of reflection will be introduced in the next article

Reflection is when Java runs (run time) an ability that can access, detect and modify its own state or behavior. It allows running Java programs to obtain their own information and operate on the internal properties of classes or objects. Class class introduction: Java virtual machine manages a class object for each type, which contains class related information. It is generated when compiling Java class files through javac The same name The class file holds the class object of the class, and the JVM loads a class Class file. Class and Java Lang. reflect provides support for reflection together with Java The relationships of the most commonly used classes in lang.reflect package are as follows: the three main classes field, method and constructor are used to describe the domain, method and constructor of a class respectively. They have a common parent class accessibleobject, which provides the function of access control checking. Field: describes the field (attribute) of the class. You can use get () and set () methods to read and modify the fields associated with the field object; Method: describes the method of the class. You can use the invoke () method to call the method associated with the method object; Constructor: constructor that describes a class. You can use constructor to create new objects. Next, we will learn the java reflection mechanism through several programs.

We specifically define two classes, person and employee. Employee inherits from person and each has a private, protected and public modified domain (attribute). Employee also has a private and public modified method, public class person{

There are three ways to obtain class objects: using the forname static method of class; Get the class of an object directly; Call the getClass () method of an object

public class ClassTest {
    public static void main(String[] args) throws ClassNotFoundException,illegalaccessexception,InstantiationException {
        Class c1 = Class.forName("reflect.Employee");   // 第1种,forName 方式获取Class对象
        Class c2 = Employee.class;      // 第2种,直接通过类获取Class对象
        Employee employee = new Employee("小明","18","写代码",1,"Java攻城狮",100000);
        Class c3 = employee.getClass();    // 第3种,通过调用对象的getClass()方法获取Class对象
    if (c1 == c2 &amp;&amp; c1 == c3) {     // 可以通过 == 比较Class对象是否为同<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>对象
        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println("c1、c2、c3 为同<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>对象");
        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(c1);     // class reflect.Employee
    }
}

}

There are two main ways to generate objects through reflection

public class NewInstanceTest {
    public static void main(String[] args) throws illegalaccessexception,InstantiationException,NoSuchMethodException,InvocationTargetException {
        Class c = Date.class;
        Date date1 = (Date) c.newInstance();    // 第1种方式:使用Class对象的newInstance()方法来创建Class对象对应类的实例
        System.out.println(date1);      // Wed Dec 19 22:57:16 CST 2018
    long timestamp =date1.getTime();
    Constructor constructor = c.getConstructor(long.class); 
    Date date2 = (Date)constructor.newInstance(timestamp);  // 第2种方式:先通过Class对象<a href="https://www.jb51.cc/tag/huoqu/" target="_blank" class="keywords">获取</a>指定的Constructor对象,再<a href="https://www.jb51.cc/tag/diaoyong/" target="_blank" class="keywords">调用</a>Constructor对象的newInstance()<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>来创建实例
    Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(date2);  // Wed Dec 19 22:57:16 CST 2018
}

}

We have defined two classes above. Now we have a requirement: get the class name of employee, constructor signature, all methods, all fields (attributes) and values, and then print them. What is the way to implement it?

Yes, you guessed right. You can get the information of these classes through reflection. In the above introduction, we know that the JVM virtual machine manages a class object for each type,

In order to fulfill our requirements, we need to know some APIs as follows:

String getname() gets the class name of this class. Constructor [] getdeclaraedconstructors() returns the object array of all constructors of this class, including protected and private constructors; The similar method getconstructors() returns the object array of all public constructors of this class, excluding protected and private constructors. Method [] getdeclaredmethods() returns all methods of this class or interface, including protected and private methods, excluding superclass methods; The similar method getmethods() returns the object array of the public methods of this class and its superclass, excluding the protected and private methods. Field [] getdeclaredfields() returns the object array of all fields of this class, including the protected and private fields, excluding the superclass fields; There is also a similar API getfields(), which returns the object array of the public domain of this class and its superclass, excluding the protection domain and private domain. Int getmodifiers() returns an integer value used to describe the modifiers of field, method and constructor. The meaning represented by this value can be analyzed through the modifier class, which provides information about field Method, constructor, etc. to access the modifier information. The main methods are: toString (int modifiers) returns the string of the modifier represented by the integer value modifiers; Whether isabstract is modified by abstract; Whether isvolatile is modified by volatile; Whether isprivate is private; Whether isprotected is protected; Whether ispublic is public; Whether isstatic is a static modifier; Wait, see the name

public class ReflectionTest {

We have obtained the class information above, and now we have another requirement: to view the actual value of the object's data field at runtime. This scenario is like when we set a breakpoint to intercept the program through the idea debugger and view the value of the property of an object. We know that the java reflection mechanism provides an API for viewing class information, so it should also provide an API for viewing the actual value of the field field and setting the actual value of the field. Yes, you guessed right, there are relevant APIs, but there is a question. Some attributes are private fields modified by private. Can you view and set them directly? After reading the API below, you can know the answer

Class getcomponenttype() returns the class of the component type in the array class. If it is not an array class, null Boolean isarray() returns whether the class is an array. APIs of the same type include int array such as isannotation, isasciidigit, isenum, isinstance, isinterface, islocalclass, isprimitive, etc Getlength (obj) returns the length of the array object obj, object array Get (obj, I) gets the element with index I of the array object. Boolean isprimitive () Returns whether this class is one of the eight basic types, that is, whether it is Boolean, byte, char, short, long, float, double and other primitive types. Field getfield (string name) gets the domain object accessibleobject with the specified name Setaccessible (fields, true) when accessing field, method and constructor, Java will perform access check. If the visitor does not have permission, a SecurityException will be thrown. For example, the visitor cannot access the private decorated domain. By setting setaccessible (true), you can cancel the execution access check of Java, so that the visitor can obtain the access permission of the specified field, method or constructor class field GetType () returns a class object that identifies the declaration type of the field represented by this field object Get (object obj) gets the actual value of the attribute represented by the current domain object on the obj object. What you get is an object object, which needs to be converted into an actual type in actual use, or you can directly obtain the specific type value void field through getbyte(), getchar, getint() Set (object obj, object value) sets the actual value of the attribute represented by the current field on the obj object

After understanding the above related APIs, we knock out the following program to verify the public class objectanalyzer{

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>