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--
Editor to share with you what is the use of Java reflection, I hope you will learn something after reading this article, let's discuss it together!
Review: what is reflection?
Reflection is one of the characteristics of Java, which allows running Java programs to get their own information and manipulate the internal properties of classes or objects.
Oracle's official explanation 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.
Java reflection mainly provides the following functions:
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 that any class has at run time (you can even call the private method through reflection)
Call the method of any object at run time
Important: run time, not compile time
Second, the 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 Bean through XML files). In order to ensure the versatility of the framework, they may need to load different objects or classes according to the configuration file and call different methods, so reflection must be used to dynamically load objects that need to be loaded at run time.
For example, in development using the 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, which is inseparable from 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.
Third, 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 use and implementation of basic reflection functions (reflection-related classes are generally in the java.lang.relfect package).
1. Get the Class object
There are three ways:
(1) use the forName static method of the Class class:
Public static Class forName (String className) ```for example, this method is often used in JDBC development to load the database driver:``` java Class.forName (driver)
(2) obtain the class of an object directly, such as:
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 (); 2. 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); 3. Create an instance
There are two main ways to generate objects through reflection.
Use the newInstance () method of the Class object to create an instance of the corresponding class of the Class object.
Class c = String.class;Object str = c.newInstance ()
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 of String class Constructor constructor = c.getConstructor (String.class) with one String parameter; / / create an instance Object obj = constructor.newInstance ("23333") according to the constructor; System.out.println (obj); 4. 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 does not include inherited methods.
Public Method [] getDeclaredMethods () throws SecurityException
The getMethods method returns all the public methods of a class, including the common 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, followed by the parameter of the method that corresponds to the object of the 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:
Package org.ScZyhSoft.common;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class test1 {public static void test () throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {Class c = methodClass.class; Object object = c.newInstance (); Method [] methods = c.getMethods (); Method [] declaredMethods = c.getDeclaredMethods () / / get the add method of the methodClass class Method method = c.getMethod ("add", int.class, int.class); / / all methods obtained by the getMethods () method System.out.println ("getMethods acquisition method:"); for (Method m:methods) System.out.println (m) / / all methods obtained by the getDeclaredMethods () method System.out.println ("method of getDeclaredMethods acquisition:"); for (Method m:declaredMethods) System.out.println (m);}} class methodClass {public final int fuck = 3; public int add (int a-line int b) {return aint b;} public int sub (int a-line int b) {return aqb }}
The result of running the program is as follows:
The method to obtain getMethods:
Public int org.ScZyhSoft.common.methodClass.add (int,int)
Public int org.ScZyhSoft.common.methodClass.sub (int,int)
Public final void java.lang.Object.wait () throws java.lang.InterruptedException
Public final void java.lang.Object.wait (long,int) throws java.lang.InterruptedException
Public final native void java.lang.Object.wait (long) throws java.lang.InterruptedException
Public boolean java.lang.Object.equals (java.lang.Object)
Public java.lang.String java.lang.Object.toString ()
Public native int java.lang.Object.hashCode ()
Public final native java.lang.Class java.lang.Object.getClass ()
Public final native void java.lang.Object.notify ()
Public final native void java.lang.Object.notifyAll ()
The method to obtain getDeclaredMethods:
Public int org.ScZyhSoft.common.methodClass.add (int,int)
Public int org.ScZyhSoft.common.methodClass.sub (int,int)
As you can see, the method obtained through getMethods () can get the methods of the parent class, such as the methods defined under java.lang.Object.
5. Get 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 T newInstance (Object... Initargs)
This method can call the corresponding Constructor to create an object instance based on the parameters passed in.
6. Get 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 member variables of their parent class
The usage of getFileds and getDeclaredFields methods is the same as above (see Method).
7. 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, InvocationTargetException
Here is an example:
Public class test1 {public static void main (String [] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {Class klass = methodClass.class; / / create an instance of methodClass Object obj = klass.newInstance (); / / get the add method Method method = klass.getMethod ("add", int.class,int.class) of the methodClass class / / call the method corresponding to method = > add (1heli4) Object result = method.invoke (obj,1,4); System.out.println (result);}} class methodClass {public final int fuck = 3; public int add (int aline int b) {return aint b;} public int sub (int a minint b) {return aint b;}}
For a detailed explanation of the invoke method, I will write a special article to delve into the process of invoke.
8. 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 static void testArray () throws ClassNotFoundException {Class cls = Class.forName ("java.lang.String"); Object array = Array.newInstance (cls,25); / / 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));}
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, post the source code:
Private static native Object newArray (Class componentType, int length) throws NegativeArraySizeException
Source directory: openjdk\ hotspot\ src\ share\ vm\ runtime\ reflection.cpp
ArrayOop Reflection::reflect_new_array (oop element_mirror, jint length, TRAPS) {if (element_mirror = = NULL) {THROW_0 (vmSymbols::java_lang_NullPointerException ());} if (length
< 0) { THROW_0(vmSymbols::java_lang_NegativeArraySizeException()); } if (java_lang_Class::is_primitive(element_mirror)) { Klass* tak = basic_type_mirror_to_arrayklass(element_mirror, CHECK_NULL); return TypeArrayKlass::cast(tak)->Allocate (length, THREAD);} else {Klass* k = java_lang_Class::as_Klass (element_mirror); if (k-> oop_is_array () & & ArrayKlass::cast (k)-> dimension () > = MAX_DIM) {THROW_0 (vmSymbols::java_lang_IllegalArgumentException ());} return oopFactory::new_objArray (k, length, THREAD);}}
In addition, the set and get methods of the Array class are both native methods, which correspond to Reflection::array_set and Reflection::array_get methods in HotSpot JVM, so I won't parse them in detail here.
IV. Some points for attention in reflection
Because reflection consumes some additional system resources, you don't need to use reflection if you don't need to create an object dynamically.
In addition, permission checking can be ignored when reflection calls methods, which can break encapsulation and cause security problems.
After reading this article, I believe you have a certain understanding of "what is the use of Java reflection". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
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.