In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to understand Java reflection technology". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. Prophase summary 1. What is reflection?
When the Java reflection mechanism is running, for any class, you can know all the properties and methods of that class; for any object, you can call any of its methods and properties. This function of dynamically fetching information and dynamically calling methods of objects is called the reflection mechanism of java. Inverse understanding of reflection: you don't know in advance what type of object you need to use before you use it. It is only at the time of the call that you know the type of object to call. The opposite is the understanding of the opposite in reflection. Program execution is divided into compiler and run time, loading a class at compilation time is called static loading class, and running time loading class is called dynamic loading class. The core idea allows you to write code with more flexibility, reduce coupling and improve code adaptability. The reflection framework provides the following common core functions: 1. Judge the class to which any object belongs at run time; 2. Construct an object of any class at run time; 3. Determine the member variables and methods of any class at run time (you can even call the private method through reflection); 4. Call the method of any object at run time
2. The main uses of reflection
General framework, many frameworks are configured (for example, Spring configures Bean through xml). In order to ensure the versatility of the framework, you may need to load different objects or classes according to different configuration files and call different methods, which requires reflection and dynamic loading of objects to be loaded at run time.
3. Shortcomings
Poor performance-because java reflects dynamic parsing types, it involves processing that scans the classpath to find classes to load, resulting in poor performance.
Security restrictions-Reflection requires runtime permissions, which may not apply to systems running under Security Manager. This may cause the application to fail at run time because of the security manager.
Security issues-using reflection, we can access parts of the code that we should not access, for example, we can access the private field of the class and change its value. This can be a serious security threat and cause your application to behave abnormally.
High maintenance-reflective code is difficult to understand and debug, and any problems with the code cannot be found at compile time, because these classes may not be available, making them less flexible and difficult to maintain.
00001. Class object
00002. Class name
00003. Modifier
00004. Packet information
00005. Parent class
00006. Implemented interface
00007. Constructor
00008. Method
00009. Variable
00010. Notes
Second, get the Class object
At run time, a class, only one Class object is generated
1. Static methods of the class (commonly used):
00001. Describes the Class object that gets the full path of the specified class associated class or interface.
00002. Method / / Mastering public static Class forName (String className) / / understanding public static Class forName (String className, boolean initialize,ClassLoader loader)
00003. Take a chestnut Class clazz = Class.forName ("http://com.wener.reflect.Xxx")// or Class clazz = Class.forName (" http://com.wener.reflect.Xxx",initialize,this.getClass().getClassLoader))
1. Indicates that any data type (including the basic data type) has a "static" class attribute
two。 Method Class cls = type .class
3. Take a chestnut Class cls = String.class;System.out.println (cls.toString ())
1. Indicates that the Class object is returned through an instance of the object
two。 Method Class cls = instance.getClass ()
3. Take Chestnut public class User {} User user = new User (); Class cls = Class.forName ("com.wener.reflect.demo1.User"); / * get the property exposed by the specified name of the class * / Field detail = cls.getField ("detail"); System.out.println (detail); / * * get the property of the specified name of the class (including private attributes) * / Field name = cls.getDeclaredField ("name"); System.out.println (name) } catch (ClassNotFoundException | NoSuchFieldException e) {e.printStackTrace ();}}
1. It shows that reflection is very powerful, but after learning, you don't know how to use it, but you don't think it is as direct and convenient as calling the method directly. But we won't have any feelings until we come into contact with some frames later.
two。 Test class package com.wener.reflect.demo2; public class ReflectDemo1 {public void say () {System.out.println ("ReflectDemo1");}} public class ReflectDemo2 {public void say () {System.out.println ("ReflectDemo2");}}
3. Configuration file reflect.propertiesclass=ReflectDemo2. Method=say
4. Test code public static void main (String [] args) {/ / get the class name and method name from spring.txt File springConfigFile = new File ("/ Users/zhangwei/work/IdeaProjects/JavaExample/ReflectExample/src/reflect.properties"); Properties properties = new Properties (); try {properties.load (new FileInputStream (springConfigFile)); String className = (String) properties.get ("class"); String methodName = (String) properties.get ("method") / / get the class object Class cls = Class.forName (className) according to the class name; / / get the method object Method m = cls.getMethod (methodName) according to the method name; / / instantiate the object Object service = cls.newInstance () according to the constructor; / / call the specified method m.invoke (service) of the object;} catch (IOException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException | InstantiationException e) {e.printStackTrace ();}}
5. Advantages when you need to switch from calling the method of the first class to calling the method of the second class, there is no need to modify a line of code
1. Dynamic switching through configuration files. VI. Comprehensive case return value method description String getName () gets the name of the method int getModifiers () gets the method's modifier Class getReturnType () Type getGenericReturnType returns the method's return value type Class [] getParameterTypes () Type [] getGenericParameterTypes () returns the method's parameters (list) Class [] getExceptionTypes () Type [] getGenericExceptionTypes () returns the method's exception information 4, other API
1. Take Chestnut public class User {private String name = "Wood"; public String detail = "hello"; private int age; private BigDecimal balance; public void increment () {this.age++; System.out.println (age);} public BigDecimal getBalance () {return balance;} public void setBalance (BigDecimal balance) {this.balance = balance;} private void say (int num) {System.out.println (num + "technician") } @ Override public String toString () {return "User {" + "name='" + name +'\'+ ", detail='" + detail +'\'+'}';}} public class TestReflectUser {public static void main (String [] args) {reflectMethod ();} public static void reflectMethod () {try {/ / 1. Instantiate the class object Class cls = Class.forName ("com.wener.reflect.demo1.User"); / / 2. Instantiate the User object Object o = cls.newInstance (); / / 3. Get set method Method method = cls.getMethod ("increment"); / 4 execute method method.invoke (o); / / have parameters and no return values Method setBalance = cls.getMethod ("setBalance", BigDecimal.class); Object methodSet = setBalance.invoke (o, new BigDecimal (100.00)); System.out.println (methodSet); / / return values without parameters Method methodGet = cls.getMethod ("getBalance"); Object invoke = methodGet.invoke (o); System.out.println (invoke) / / get private method Method say = cls.getDeclaredMethod ("say", int.class); / / Runtime cancel access detection mechanism say.setAccessible (true); / / execute method say.invoke (o, 1);} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace ();}
Assign the result of the method represented by the object on the obj using the parameter args
1. Method Object invoke (Object obj, Object...) Args)
two。 Parameter description
Obj-the object from which the underlying method is called, which must be an instantiated object
Args-the parameter for the method call, which is an Object array because there may be more than one parameter
1. Return value
3. Call method
1. 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// returns all the public methods of a class, including the public methods of its inherited class. Public Method [] getMethods () throws SecurityException
two。 Take chestnut public class TestReflectUser {public static void main (String [] args) {reflectMethod ();} public static void reflectMethod () {try {/ / 1. Instantiate the class object Class cls = Class.forName ("com.wener.reflect.demo1.User"); / / 2. Instantiate User object Object o = cls.newInstance (); / / get all common methods (including parent class methods) Method [] methods = cls.getMethods (); for (Method method1: methods) {System.out.println (method1.getName ());} / / get all methods (including private, public, default) Method [] declaredMethods = cls.getDeclaredMethods (); for (Method declaredMethod: declaredMethods) {System.out.println (declaredMethod.getName ()) }} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace ();}
2. Get all the methods
1. Method / / method returns a specific method, where the first parameter is the method name, and the following parameter is the method parameter corresponding to the object public Method getMethod (String name, Class...) of Class ParameterTypes)
two。 Take Chestnut public class User {private String name = "Wood"; public String detail = "hello"; private int age; private BigDecimal balance; public void increment () {this.age++; System.out.println (age);} public BigDecimal getBalance () {return balance;} public void setBalance (BigDecimal balance) {this.balance = balance;} private void say (int num) {System.out.println (num + "technician") } @ Override public String toString () {return "User {" + "name='" + name +'\'+ ", detail='" + detail +'\'+'}';}} public class TestReflectUser {public static void main (String [] args) {reflectMethod ();} public static void reflectMethod () {try {/ / 1. Instantiate the class object Class cls = Class.forName ("com.wener.reflect.demo1.User"); / / 2. Instantiate the User object Object o = cls.newInstance (); / / 3. Get increment method Method method = cls.getMethod ("increment"); / / have parameters and no return values Method setBalance = cls.getMethod ("setBalance", BigDecimal.class); / / have return values without parameters Method methodGet = cls.getMethod ("getBalance"); / / get private methods Method say = cls.getDeclaredMethod ("say", int.class);} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace ();}
1. Get a single method. 5. Method operation
1. Method / / sets the field represented by this Field object on the specified object parameter to the specified new value field.set (Object obj,Object value)
two。 Parameter description
Object obj: the instance object of the class in which the field is located
Object value: new valu
1. Note / / if you want to assign values to private variables, you must cancel the access control field.setAccessible (true) for permissions.
two。 Take Chestnut public static void main (String [] args) {try {/ / 1 instantiate the Class object Class cls = Class.forName ("com.wener.reflect.demo1.User"); / * * get the public attribute of the specified name of the class * / Field detail = cls.getField ("detail"); System.out.println (detail) / * get all the attributes of the class (including private default public) * / Field name = cls.getDeclaredField ("name"); / / 2. Create the object Object o = cls.newInstance (); / 3 set name.set (o, "Jiaojiao"); System.out.println (o.toString ()) through the set method of the field;} catch (ClassNotFoundException | NoSuchFieldException | InstantiationException | IllegalAccessException e) {e.printStackTrace ();}}
4. Field assignment
1. Method / / get all public fields Field [] getFields () / / get all fields (private, protected, default, public) Field [] getDeclaredFields ()
two。 Take Chestnut public class TestReflectUserField {public static void main (String [] args) {try {Class cls = Class.forName ("com.wener.reflect.demo1.User"); Field [] fields = cls.getFields (); for (Field field: fields) {System.out.println ("Type:" + field.getType () + "method name:" + field.getName ());} Field [] declaredFields = cls.getDeclaredFields () For (Field declaredField: declaredFields) {System.out.println ("Type:" + declaredField.getType () + "method name:" + declaredField.getName ());}} catch (ClassNotFoundException | NoSuchFieldException | InstantiationException | IllegalAccessException e) {e.printStackTrace ();}
3. Get all member fields
2. Getting the member variable of a single member field class is also an object, and it is an object of java.lang.reflect.Field, so we obtain this information and manipulate these properties through the methods encapsulated in java.lang.reflect.Field. 1, description 4, attribute operation
1. The cls.newInstance () method returns a generic T, which we need to convert to a custom class.
2. Cls.newInstance () returns the class's parameterless construction object by default
3. The class loaded by the reflection mechanism must have no parameter constructor, otherwise running will throw an exception
1.4. Note 3. Create an instance
1. Commonly used are the static methods of the class
2. GetClass () is generally used a little more in inheritance, such as the annotation framework in Android
3. .class static syntax: you need to import the package of the class, and the dependency is too strong. If you don't import the package, you will throw a compilation error.
This is the end of "how to understand Java reflection Technology". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.