You understand a text with Java reflection mechanism

Want more articles can visit my blog -  Code endless .

Last week to work when solving a demand, we need to export a batch of data to Excel. Originally the company's middleware team has a good package of tools to use POI to generate Excel methods, but the demand for the product which has helplessly requirements of a merged cell, the tools to find for a long time did not find applicable methods, you can only own line and sleeves dry. Tool ways to export Excel will ultimately use reflection, but this reflection thing for people like me to write code for business contacts is relatively small, so catching a bit, wrote this article about the record.

What is the reflection

Study the root of all things, the same study new things, first of all we need to know what it is, what to use. In the operating state, for any class, they are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information and dynamic method call object dynamically acquired feature is called reflection mechanism of Java language. Then we can use reflection to do what?

  • In the run-time analysis class.
  • View objects at runtime, we can also use reflection to write a toString method for all classes to use.
  • Using Method object, any call an object method at runtime.

Then this article will focus on three points above those who look at Java's reflection mechanism. Before we start, we first introduce a class that is essential for us to use in the process of using reflected a class.

Class class

At runtime, Java run-time system for each object maintains a identifies the object type of information, and Save as type is the Class class of such information. We can object getClass()to get the Class object for the object's method, like this below.

User user = new User();
Class c = user.getClass();

Meaning anything in this world has its existence, then we can use Class objects to do it? We most frequently used Class to determine whether an object is of a certain type, like this:

User user = new User();

if (user.getClass() == User.class) {
    System.out.println("user is User");
}

Of course, we also often use the Class class getName()method to get the name of a class. Write time, we will also use its newInstance()methods to obtain an instance of a type (not provided when such common construction method).

Analysis by the reflection type

Analysis of a class, is nothing less than to see this class of properties, methods, and its method of construction. Providing three classes in the Java reflection Field packet, Method and Constructor described properties, methods and constructors, respectively.
Here we look at are, how we access this information through a kind of reflection.
1. Obtain property

User user = new User();
Class cl = user.getClass();
Field[] fields1 = cl.getFields();
Field[] fields2 = cl.getDeclaredFields();

You can see that we can use getFields()and getDeclaredFields()two methods to get the list of properties in the class, then the two methods What difference does it make? Difference is that there are members of the class of information will only return the former, while the latter will return this information to all members of the class include public, private, protected, but does not include the parent class member information.

2. Get constructor

Constructor[] constructors1 = cl.getConstructors();
Constructor[] constructors2 = cl.getDeclaredConstructors();

3. The acquisition method

Method[] methods1 = cl.getMethods();
Method[] methods2 = cl.getDeclaredMethods();

We can see that we can easily get his attributes, constructors and methods of information via Class object of a class. But in the Field, Constructor and Method in which it was provided api do? Here we look at together.

1. getName()A method for acquiring the corresponding name. Exist in Field, Constructor and Method classes .
2. The getModifiers()method to obtain the foregoing modifier (public, etc.), but getModifiers()returns an int value, we can Modifier.toString(int i)convert it into the corresponding character string. Also exist in Field, Constructor and Method classes.
3. getParameterTypes()A method for acquiring parameters of type array method. Method and Constructor present in class
4. The getReturnType()method for obtaining the return type. Method exists only in the class

With these api, we have the ability of a class analysis at runtime, we can pass a simple little example to practice it, we can write a method to output the complete information of a class, concrete implementation will be given at the end of the text out, you can first try it yourself.

View objects using reflection

Sometimes it, we may also need to get the value of the reflection properties of the object, for example at the time of export Excel, we only know the name of the field corresponding to attribute column, then we need to get its value through reflection, and then write it to Excel. Then this section will look at how to use Java with the reflection to analyze objects.

User user = new User(1,"itweknow");
Class cl = user.getClass();
Field userName = cl.getDeclaredField("userName");
Object value = userName.get(user);

Like the above code, we can use the Fieldclass provided get(Object obj)a method to get the value of the property, also provides for a base type-specific get methods, such as getDouble(). However, if the above userNameis a private property if there is, get()the method will certainly be thrown IllegalAccessExceptionexception. This is the time we need to use setAccessible()methods covered by the security manager's access control.

User user = new User(1,"itweknow");
Class cl = user.getClass();
Field userName = cl.getDeclaredField("userName");
userName.setAccessible(true);
Object value = userName.get(user);

setAccessible()In the method Field, Method, Constructorclasses are provided. And get()methods echo, Fieldalso provides a set()method used to set the property value.

Using reflection to invoke any of the methods

Method class provided a invoke()method call, the current method of packaging Method object. invoke()The method is defined as follows:

Object invoke(Object obj, Object... args)

The first parameter of this method is to call the object, the second parameter is a parameter of the process, is in the form of an array. Here we look at how to use reflection to call Userclass sayHello()method it.

Method sayHelloMethod = cl.getDeclaredMethod("sayHello", String.class);
sayHelloMethod.setAccessible(true);
sayHelloMethod.invoke(user, "Reflect");

We look at the code above getDeclaredMethod()to obtain a method called sayHelloprivate method (PS: If the method is public, then the direct use of getMethod()the method on it), also for the private way, we need to modify its access control can be successfully invoked.

API finishing

The above-mentioned chapters in the Api lot of Java reflection mechanism provided, the following is my finishing some common reflection Api, you can refer to.

1.Class class

Api description
forName () Returns the Class object of the specified class name
newInstance() It returns a new instance of this class
getFields() This class returns all public properties
getDeclaredField() This class returns all properties (including public, private, protected)
getMethods() All total return method in this class
getDeclaredMethods() Return all methods of this class (includes public, private, protected)
getConstructors() Returns the class of all public constructors
getDeclaredConstructors() Return all of the class constructor (includes public, private, protected)
getField() & getDeclaredField() Returns the name of the class attribute specified
getMethod() & getDeclaredMethod() Returns the specified method name and parameters
cl.getConstructor() & cl.getDeclaredConstructor() Get the specified parameter constructor

2.Field class

Api description
getModifiers() Returns the integer value of modifiers used to describe a property. Modifier class using toString()a method which was converted to a string.
getName() Jiong return a string for the name attribute described.

3.Method class

Api description
getModifiers() Returns the integer value of a modifier for the method described. Modifier class using toString()a method which was converted to a string.
getName() Jiong back a string for the name of the method described.
getParameterTypes() It returns an array of Class objects described for parameter type.
GetReturnType () Returns used to describe a type of Class H returned objects.
invoke() This method is called the object described, pass a given parameter, and returns the return value of the method.

4.Constructor class

Api description
getModifiers() Returns the integer value used to describe a modifier constructor. Modifier class using toString()a method which was converted to a string.
getName() Return a string used to describe Jiong constructor name.
getParameterTypes() It returns an array of Class objects described for parameter type.

5.AccessibleObject类

Api description
setAccessible(boolean flag) Settings can be accessed flag reflecting object. flag to true indicates that block access to check the Java language, so that the private property of an object can be queried and set.
isAccessible () Returns the value reflecting object can access flag.

Conclusion

This article and everyone learned about Java's reflection mechanism, as well as in the reflective package Field, Method, ConstructorAPI provided by the three classes. In the use of reflective analysis class section, I mentioned the complete information about the use of reflective print category, the specific implementation code Click here to get . I hope this article can help you. Finally, if you like, then this article is welcome at Github source project point of a Star.

PS: Learn more than, non-stop code hoof! If you like my articles, it concerns me!

Scan code concern "Code indefinitely"

Guess you like

Origin www.cnblogs.com/endless-code/p/11261558.html