In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the use of reflection in Java". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the use of reflection in Java"?
Review: what is reflection?
Reflection is one of the features of Java programming language, which allows running Java programs to obtain their own information and manipulate the internal properties of classes or objects.
Oracle's official interpretation of reflection is
Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.
The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. It also allows programs to suppress default reflective access control.
in short, through reflection, we can get information about the members and members of each type of program or assembly at run time.
The general types of objects in the program are determined at compile time, while the Java reflection mechanism can dynamically create objects and call their properties, the type of such objects is unknown at compile time. So we can create an object directly through the reflection mechanism, even if the type of the object is unknown at compile time.
The core of reflection is that JVM dynamically loads classes or calls methods / access properties at run time, and it doesn't need to know in advance (at code-time or compile-time) who the running object is.
The Java reflection framework mainly provides the following functions:
1. Determine the class to which any object belongs at run time
two。 Construct an object of any class at run time
3. Determine the member variables and methods that any class has at run time (you can even call the private method through reflection)
4. Call the method of any object at run time
Important: run time, not compile time
Main uses of reflection
many people think that reflection is not widely used in actual Java development, but it is not.
when we are using IDE (such as Eclipse,IDEA), when we enter an object or class and want to call its properties or methods, the compiler will automatically list its properties or methods as soon as we press the period, and reflection will be used here.
The most important use of reflection is to develop a variety of general frameworks.
many frameworks (such as Spring) are configured (such as configuring JavaBean,Action through XML files). In order to ensure the versatility of the framework, they may need to load different objects or classes and call different methods according to the configuration file, which requires reflection-- dynamically loading objects that need to be loaded at run time.
to give an example, in the development of Struts 2 framework, we usually configure Action in struts.xml, such as:
/ shop/shop-index.jsp login.jsp
The configuration file establishes a mapping relationship with Action. When a request is made by the View layer, the request is intercepted by StrutsPrepareAndExecuteFilter, and then StrutsPrepareAndExecuteFilter dynamically creates the Action instance.
For example, if we request login.action, StrutsPrepareAndExecuteFilter will parse the struts.xml file, retrieve the Action with name as login in action, create an instance of SimpleLoginAction based on the class attribute, and call the execute method with the invoke method. This process cannot be done without reflection.
For framework developers, reflection is small but very useful, and it is the core of various container implementations. For the average developer, if you don't go deep into the framework, you will use less reflection, but it is also useful to understand the underlying mechanism of the framework to enrich your programming ideas.
The basics of reflection: about the Class class
For more information on the principle and introduction of Class class and Object class, see the previous section.
1. Class is a class, a class that describes the class (that is, the class itself), which encapsulates the Method of the description method, the Filed of the description field, the Constructor of the constructor, and so on.
2. The information that can be obtained after the object looks in the mirror (reflected): the data member name, method and constructor of a class, and which interfaces are implemented by a class.
3. For each class, JRE retains an object of immutable Class type. A Class object contains information about a particular class.
4. Class objects can only be created by the system
5. A class will have only one Class instance in JVM
/ / to sum up, JDK has a class called Class, which is used to encapsulate all Java types, including all the information about these classes. The class information in JVM is placed in the method area. / / after all classes are loaded, JVM will create a Class object for it in the heap, and each class will have only one Class object, and all objects of this class will be instantiated through Class. / / the above is the principle of JVM instantiation, of course, in fact, when writing code in Java, you only need to use the class name to instantiate. Public final class Class implements java.io.Serializable, GenericDeclaration, Type, AnnotatedElement {Virtual machines remain unique / / get unique Class objects through the class name .class. Class cls = UserBean.class; / / get the Class object through integer.TYPEl Class inti = Integer.TYPE; / / interface is essentially a class, you can also get Class userClass = User.class through .class
JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic information acquisition and the function of dynamically calling the methods of the object is called the reflection mechanism of java language.
To dissect a class, you must first get the bytecode file object of the class. The dissection uses the method in the Class class. So first get the Class type object corresponding to each bytecode file.
The summary above is what is reflection.
Reflection is to map the various components of the java class into Java objects one by one.
For example: a class has: member variables, methods, constructors, packages and other information, the use of reflection technology can be used to dissect a class and map each component into an object. (in fact: these member methods, constructors, and adding classes in a class are all described by a class.)
As shown in the figure, the normal loading process of the class: the principle of reflection is with the class object.
Familiarize yourself with loading: the origin of the Class object is to read the class file into memory and create a Class object for it.
Why does Java need reflection? What is the problem of reflection?
There are two types of compilation in Java:
Static compilation: the type is determined at compile time, and the binding object is passed.
Dynamic compilation: the runtime determines the type and binds the object. Dynamic compilation maximizes the flexibility of Java, reflects the application of polymorphism, and can reduce the coupling between classes.
Java reflection is a key property of Java as a dynamic (or quasi-dynamic) language. This mechanism allows a program to obtain internal information about any class with a known name through Reflection APIs, including its modifiers (such as public, static, etc.), superclass (such as Object), implemented interfaces (such as Cloneable), as well as all information about fields and methods, and can change the fields content or evoke methods at run time.
Reflection can load, discover, and use classes that is completely unknown at compile time at run time. That is, the Java program can load a class whose name is known only at run time, get its complete construction, and generate its object entity, or set its fields value, or evoke its methods.
Reflection allows static languages to check and modify the structure and behavior of programs at run time (runtime).
In a static language, when using a variable, you must know its type. In Java, the type information of variables is saved to the class file at compile time, so that the accuracy is guaranteed at run time; in other words, the behavior of the program at run time is fixed. If you want to change at run time, you need to reflect this thing.
The classes that implement the Java reflection mechanism are located in the java.lang.reflect package:
Class class: represents a class
Field class: member variables that represent the class (properties of the class)
Method class: a method that represents a class
Constructor class: the constructor that represents the class
Array class: provides static methods for dynamically creating arrays and accessing the elements of the array
In a word, the use of reflection can give jvm the ability to compile dynamically, otherwise the metadata information of the class can only be realized by static compilation, such as hot loading, classloader of Tomcat, and so on.
The basic application of reflection
We mentioned above that reflection can be used to determine the class to which any object belongs, get a Class object, construct any object, and call an object. Here we introduce the implementation of basic reflection functions (reflection-related classes are usually in the java.lang.relfect package).
1. There are three ways to obtain Class objects.
(1) use the forName static method of the Class class:
Public static Class forName (String className) ```is often used to load the database driver in JDBC development: to load this class with the full class name, the configuration information of the general database driver will be written in the configuration file. Import jar package ```java Class.forName (driver) before loading this driver
(2) obtain the class of an object directly, such as:
/ / Class is a generic representation that gets the type of a class. Class klass = int.class;Class classInt = Integer.TYPE
(3) call the getClass () method of an object, such as:
StringBuilder str = new StringBuilder; Class klass = str.getClass (); determine whether it is an instance of a class
In general, we use the instanceof keyword to determine whether it is an instance of a class. At the same time, we can also use the isInstance () method of the Class object in reflection to determine whether it is an instance of a class, which is a Native method:
= = public native boolean isInstance (Object obj); =
Create an instance
There are two main ways to generate objects through reflection.
(1) use the newInstance () method of the Class object to create an instance of the corresponding class of the Class object.
Note: create objects with newInstance: the called class must have a constructor with no parameters
/ / Class represents a class object of any class. / / use this class object to instantiate other classes / / because jvm automatically generates a corresponding * .Class object in the heap area after loading the class. / this object is used to instantiate all * objects in JVM pairs. Class c =? in String.class;//Class? Is a wildcard, in fact, it represents any class that meets the criteria for the definition of a generic class, which is basically the same as using Class// directly, but it is more standardized to avoid unnecessary unchecked errors when converting some types. Object str = c.newInstance ()
(2) first get the specified Constructor object through the Class object, and then call the newInstance () method of the Constructor object to create the instance. This method can construct an instance of the class with the specified constructor.
/ / get the Class object corresponding to String Class c = String.class;// get the constructor Constructor constructor = c.getConstructor (String.class) of the String class with one String parameter; / / create an instance Object obj = constructor.newInstance ("23333") based on the constructor; System.out.println (obj); get method
To get a collection of methods for a Class object, there are mainly the following methods:
The getDeclaredMethods () method returns all methods declared by the class or interface, including public, protected, default (package) access, and private methods, but not inherited methods.
Public Method [] getDeclaredMethods () throws SecurityException
The getMethods () method returns all public methods of a class, including the public methods of its inherited class. = =
Public Method [] getMethods () throws SecurityException
The getMethod method returns a specific method, where the first parameter is the method name and the subsequent parameter is the parameter of the method that corresponds to the object of Class
Public Method getMethod (String name, Class... ParameterTypes)
It's just that this description may be difficult to understand, and we use examples to understand these three methods:
The examples in this article use the following classes for reflection testing.
/ / Annotation class, which can be used to express the method, and the content of the annotation can be obtained by reflection. / / the implementation of Java annotations is the basis for many annotation frameworks to implement annotation configuration @ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) public @ interface Invoke {}
Personbean, parent class of userbean
Public class PersonBean {private String name;int id;public String getName () {return name;} public void setName (String name) {this.name = name;}
}
Interface user
Public interface User {public void login ();}
UserBean implements the user interface and inherits personbean
Public class UserBean extends PersonBean implements User {@ Override public void login () {} class B {} public String userName; protected int i; static int j; private int l; private long userId; public UserBean (String userName, long userId) {this.userName = userName; this.userId = userId;} public String getName () {return userName;} public long getId () {return userId @ Invoke public static void staticMethod (String devName,int a) {System.out.printf ("Hi% s, I'm a static method", devName);} @ Invoke public void publicMethod () {System.out.println ("I'm a public method");} @ Invoke private void privateMethod () {System.out.println ("I'm a private method");}}
1 the difference between getMethods and getDeclaredMethods
Public class dynamically loads the reflection of the class {public static void main (String [] args) {try {Class clazz = Class.forName ("com.javase. Reflection .UserBean "); for (Field field: clazz.getDeclaredFields ()) {/ / field.setAccessible (true); System.out.println (field);} / / getDeclaredMethod* () gets all the methods declared by the class itself, including the public, protected, and private methods. System.out.println ("- common methods -"); / / getDeclaredMethod* () gets all the methods declared by the class itself, including the public, protected, and private methods. / / getMethod* () gets all the common methods of the class, including all its own public methods, and all public methods inherited from the base class and implemented from the interface. For (Method method: clazz.getMethods ()) {String name = method.getName (); System.out.println (name); / / prints out all the methods of UserBean.java and the methods of the parent class} System.out.println ("- exclusive method -") For (Method method: clazz.getDeclaredMethods ()) {String name = method.getName (); System.out.println (name);} catch (ClassNotFoundException e) {e.printStackTrace ();}
2 print all the methods and details of a class:
Public class prints all methods {public static void main (String [] args) {Class userBeanClass = UserBean.class; Field [] fields = userBeanClass.getDeclaredFields (); / / Note that you can't get the name of a local variable when printing a method, because jvm only knows its type Method [] methods = userBeanClass.getDeclaredMethods (). For (Method method: methods) {/ / gets the modifier of the method in turn, returns the type and name, plus the parameter String methodString = Modifier.toString (method.getModifiers ()) + "; / / private static methodString + = method.getReturnType (). GetSimpleName () +"; / / void methodString + = method.getName () + "(" / / staticMethod Class [] parameters = method.getParameterTypes (); Parameter [] p = method.getParameters (); for (Class parameter: parameters) {methodString + = parameter.getSimpleName () + "; / / String} methodString + =") "; System.out.println (methodString) } / / Note that the method can only get its type, but not the variable name / * public String getName () public long getId () public static void staticMethod (String int) public void publicMethod () private void privateMethod () * /}} to get the constructor information
The usage of the get class constructor is similar to that of the above acquisition method. You mainly get an instance of the Constructor class through the getConstructor method of the Class class, while the Constructor class has a newInstance method that creates an object instance:
Public class print construction method {public static void main (String [] args) {/ / constructors Class clazz = UserBean.class; Class userBeanClass = UserBean.class; / / get all the construction methods Constructor [] constructors = userBeanClass.getDeclaredConstructors (); for (Constructor constructor: constructors) {String s = Modifier.toString (constructor.getModifiers ()) + " S + = constructor.getName () + "("; / / the parameter type of the constructor Class [] parameters = constructor.getParameterTypes (); for (Class parameter: parameters) {s + = parameter.getSimpleName () + ",";} s + = ")"; System.out.println (s) / / print the result / / public com.javase. Reflection .UserBean (String, long,)} gets the member variable (field) information of the class
These are the main methods, and I will not repeat them here:
GetFiled: access public member variables
GetDeclaredField: all declared member variables. But cannot get the member variable of its parent class
The usage of getFileds and getDeclaredFields are the same as above (see Method)
Public class print member variable {public static void main (String [] args) {Class userBeanClass = UserBean.class; / / get all member variables of this class, including static private Field [] fields = userBeanClass.getDeclaredFields (); for (Field field: fields) {/ / private attribute can access / / field.setAccessible (true) even without the following statement / / because the private domain of the class defaults to access in reflection, administrators defaults to true. String fieldString = ""; fieldString + = Modifier.toString (field.getModifiers ()) + "; / / `private` fieldString + = field.getType (). GetSimpleName () +"; / / `String` fieldString + = field.getName (); / / `userName` fieldString + = ";"; System.out.println (fieldString); / / print result / / public String userName / / protected int iPlacement / static int jintAccord / private int lumbago / private long userId;}} call method
When we get a method from the class, we can call it with the invoke () method. The prototype of the invoke method is:
Public Object invoke (Object obj, Object... Args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetExceptionpublic class use reflection call methods {public static void main (String [] args) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {Class userBeanClass = UserBean.class; / / to get all the methods of this class, including static methods and instance methods. / / Private methods are also included here, but private methods need to set access permissions before using invoke access / / that is, use setAccessible to make methods accessible Otherwise, the exception / IllegalAccessException is interpreted as / / * An IllegalAccessException is thrown when an application tries// * to reflectively create an instance (other than an array), / / * set or get a field, or invoke a method, but the currently// * executing method does not have access to the definition of// * the specified class, field, method or constructor.// getDeclaredMethod* () gets all the methods declared by the class itself, including public, protected and private methods. / / getMethod* () gets all the common methods of the class, including all its own public methods, and all public methods inherited from the base class and implemented from the interface. / / that is, an exception is thrown when the class, domain, or method is set to private access and uses reflection calls but does not have permissions. Method [] methods = userBeanClass.getDeclaredMethods () / / get all member methods for (Method method: methods) {/ / reflection can get comments on the method Judge whether if (method.isAnnotationPresent (Invoke.class)) {/ / is modified by @ Invoke / / the modifier of the method is static if (Modifier.isStatic (method.getModifiers () {/ / if it is static method / / reflection calls the method / / Class methods can be called directly It is not necessary to instantiate method.invoke first (null, "wingjay", 2) / / call directly, and pass in the required parameter devName} else {/ / if it is not a class method, you need to get an instance before calling the method / / pass in the variable type Class [] params = {String.class, long.class} required by the constructor. / / get the constructor of the specified type of this class / / if there is no such type of method, the error Constructor constructor = userBeanClass.getDeclaredConstructor (params) will be reported. / / get the constructor whose parameter format is String,long / / instantiate Object userBean = constructor.newInstance ("wingjay", 11) through the instance of the constructor; / / instantiate using the constructor to get Object if (Modifier.isPrivate (method.getModifiers () {method.setAccessible (true) / / if it is a private method, you need to obtain its calling permission / / Set the {@ code accessible} flag for this object to// * the indicated boolean value. A value of {@ code true} indicates that// * the reflected object should suppress Java language access// * checking when it is used. A value of {@ code false} indicates// * that the reflected object should enforce Java language access checks. / / it can be set to be visible or invisible through this method. Not only can it be used in the method / / it will be used in the member variable / / print result / / I'm a public method// Hi wingjay, I'm a static methodI'm a private method} method.invoke (userBean) in the following example / / call method without parameter} to create an array using reflection
Array is a special type in Java, which can be assigned to an Object Reference. Let's take a look at an example of creating an array using reflection:
Public class creates an array {public static void main (String [] args) {Class cls = null; try {cls = Class.forName ("java.lang.String");} catch (ClassNotFoundException e) {e.printStackTrace ();} Object array = Array.newInstance (cls,25) with reflection / / add content to the array Array.set (array,0, "hello"); Array.set (array,1, "Java"); Array.set (array,2, "fuck"); Array.set (array,3, "Scala"); Array.set (array,4, "Clojure") / / get the content of an item System.out.println (Array.get (array,3)); / / Scala}}
The Array class is the java.lang.reflect.Array class. We create an array object through Array.newInstance (), whose prototype is:
Public static Object newInstance (Class componentType, int length) throws NegativeArraySizeException {return newArray (componentType, length);}
The newArray () method is a Native method. We will study its specific implementation in Hotspot JVM later. Here, we will post the source code first.
Private static native Object newArray (Class componentType, int length) throws NegativeArraySizeException;Java reflection Common interview questions what is reflection?
Reflection is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic acquisition of information and the function of dynamically calling the methods of the object is called the reflection mechanism of Java language.
Where is the reflection mechanism used?
In JDBC, the database driver is loaded dynamically by reflection.
The Web server invokes the service method of Sevlet using reflection.
Eclispe and other development tools use reflection to dynamically analyze the type and structure of objects and dynamically prompt the properties and methods of objects.
Many frameworks use reflection mechanisms, injecting properties, and calling methods, such as Spring.
What is object serialization, what is deserialization, and what needs to be done to implement object serialization?
Object serialization, the process of encoding data in an object into a sequence of bytes.
Deserialization; the process of re-decoding the encoded bytes of an object into an object.
JAVA provides API with the ability to serialize and deserialize objects. You need to follow the following conventions when using these API:
The serialized object type needs to implement the serialization interface, which is the flag interface and does not declare any abstract methods. The JAVA compiler recognizes this interface and automatically adds serialization and deserialization methods to the class.
To keep the serialization process stable, it is recommended that you add a serialized version number to the class.
Add transient if you don't want the field to be put on the hard drive.
Java serialization is required in the following situations:
When you want to save the object state in memory to a file or database
When you want to transfer objects over the network using sockets
When you want to transfer an object through RMI (remote method call).
What are the advantages and disadvantages of the reflection mechanism?
Advantages: it can be executed dynamically, and dynamically execute methods and access properties according to business functions during operation, which maximizes the flexibility of java.
Cons: it has an impact on performance, and this kind of operation is always slower than executing java code directly.
What is a dynamic agent? What are the applications?
Dynamic proxies are run-time dynamically generated proxy classes.
The applications of dynamic agent include Spring AOP data query, back-end mock of test framework, rpc,Java annotation object acquisition and so on.
How to implement dynamic proxy?
JDK native dynamic agent and cglib dynamic agent.
JDK native dynamic proxies are implemented based on interfaces, while cglib is implemented based on subclasses that inherit the current class.
The role of Java reflection mechanism
Determine the class to which any object belongs at run time
Construct an object of any class at run time
Determine the member variables and methods of any class at run time
Call the method of any object at run time
How to use the reflection of Java?
Create an object with a fully limited class name
Class.forName ("full class name"); for example, the com.mysql.jdbc.Driver Driver class has been loaded into jvm and the initialization of the class has been completed.
Class name .class; get Class clz object
Object .getClass ()
Get the constructor object and new an object through the constructor
Clazz.getConstructor ([String.class])
Con.newInstance ([parameters])
Create an instance object through the class object (equivalent to the new class name () no-parameter constructor)
Cls.newInstance ()
Get a property object through the class object
Field c=cls.getFields (): gets all the public fields of a class, including fields in the parent class.
Field c=cls.getDeclaredFields (): gets all the declared fields of a class, including public, private, and proteced, but not the declaration fields of the parent class
Get a method object through the class object
Cls.getMethod ("method name", class... ParameaType); (only public ones are available)
Cls.getDeclareMethod ("method name"); (get arbitrarily modified methods and cannot be executed privately)
M.setAccessible (true); (make private methods executable)
Let the method execute
1)。 Method.invoke (obj instance object, obj variable parameter);-(there is a return value)
Thank you for reading, the above is the content of "what is the use of reflection in Java". After the study of this article, I believe you have a deeper understanding of the use of reflection in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.