In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the example introduction of common API of Java reflection", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Java reflection of common API examples of it!"
What is reflex?
Reflection commonly used API acquires attribute information static void initUser (User user) throws IllegalAccessException {/ / gets all attributes in the User class through reflection and custom annotations (getFields cannot get the private attribute) Field [] fields = User.class.getDeclaredFields () / / iterate through all attributes for (Field field: fields) {/ / if there is this note on the attribute, assign if (field.isAnnotationPresent (InitSex.class)) {InitSex init = field.getAnnotation (InitSex.class); field.setAccessible (true); / / set the property's gender value field.set (user, init.sex (). ToString ()) System.out.println ("complete the modification of the attribute value, the modified value is:" + init.sex () .toString ());}} three ways to get the Class object
The first method: when you know the full path name of the class, you can use the Class.forName static method to get the Class object. The above example is obtained in this way:
Class clz = Class.forName ("com.choupangxia.reflect.User")
The second method: get it through ".class". The prerequisite is that the corresponding class can be obtained before compilation.
Class clz = User.class
The third: use the getClass () method of the class object.
User user = new User (); Class clz = user.getClass (); two ways to create an object
You can create an instance object of a class through the newInstance () method of the Class object and through the newInstance () method of the Constructor object.
The first: through the newInstance () method of the Class object.
Class clz = User.class;User user = (User) clz.newInstance ()
The second: through the newInstance () method of the Constructor object.
Class clz = Class.forName ("com.xxx.reflect.User"); Constructor constructor = clz.getConstructor (); User user = (User) constructor.newInstance ()
The second method to create a class object allows you to choose a specific constructor, while with a Class object you can only use the default no-parameter constructor.
Class clz = User.class;Constructor constructor = clz.getConstructor (String.class); User user = (User) constructor.newInstance ("official account"); get class properties, methods, constructors
Non-private properties are obtained through the getFields () method of the Class object.
Field [] fields = clz.getFields (); for (Field field: fields) {System.out.println (field.getName ());}
The User object properties in the above examples are all private, which cannot be obtained directly by the above method. You can change one of the attributes to public to obtain them.
Get all the properties through the getDeclaredFields () method of the Class object.
Field [] fields = clz.getDeclaredFields (); for (Field field: fields) {System.out.println (field.getName ());}
Perform the print result:
Usernameage
Of course, other values for attributes can also be obtained, and modifications to private properties require calling the field.setAccessible (true) method before assigning values. For specific applications, let's look back at our initial example of the use of annotations.
An example of the acquisition method is as follows:
Method [] methods = clz.getMethods (); for (Method method: methods) {System.out.println (method.getName ());}
Print the results:
SetUsernamesetAgegetUsernamegetAgewaitwaitwaitequalstoStringhashCodegetClassnotifynotifyAll
As you can see, you get not only the method of the current class, but also the method defined in the parent class Object class of that class.
The method of getting the constructor has been mentioned above, so I won't repeat it. These methods mentioned above all have corresponding overloaded methods in Class, which can be used flexibly according to specific conditions.
Create an array using reflection
Finally, let's look at an example of creating an array through reflection.
@ Testpublic void createArray () throws ClassNotFoundException {Class cls = Class.forName ("java.lang.String"); Object array = Array.newInstance (cls,5); / / add content Array.set (array,0, "Hello") to the array; Array.set (array,1, "official account"); Array.set (array,2, "Java"); / / get the content System.out.println (Array.get (array,2)) at the specified location in the array } an example public class User {static String country; private String name; public int age; private Result result; public void say (String world) {System.out.println ("I say:" + world);} private void writeNote () {System.out.println ("keep a diary");} public String getName () {return name;} public void setName (String name) {this.name = name } public Result getResult () {return result;} public void setResult (Result result) {this.result = result;} @ Override public String toString () {return "User {" + "name='" + name +''+ ", age=" + age +'}';}} public class ReflectTest {public static void main (String [] args) throws Exception {reflectDemo () } public static void reflectDemo () throws Exception {Class clazz = Class.forName ("kite.lab.reflect.User"); Field [] declaredFields = clazz.getDeclaredFields (); for (Field declaredField:declaredFields) {System.out.println (declaredField.getName ());} Method [] methods = clazz.getDeclaredMethods (); for (Method method:methods) {System.out.println (method.getName ()) } Object userInstance = clazz.newInstance (); Method sayMethod = clazz.getDeclaredMethod ("say", String.class); sayMethod.invoke (userInstance, "Hello"); Method writeNoteMethod = clazz.getDeclaredMethod ("writeNote"); writeNoteMethod.setAccessible (true); writeNoteMethod.invoke (userInstance);}} Summary
When it comes to reflection, everyone probably knows that the performance is poor. Then why is the performance of reflection poor?
The fundamental reason is that because reflection is dynamically loaded, the optimization that jit can do to it is extremely limited.
Jit-just-in-time compiler is a killer weapon for JVM to optimize performance. It makes a series of optimizations for hot code, such as a very important optimization tool-method inlining. Reflective code does not enjoy this treatment.
The worst performance part of reflection is the part that gets methods and attributes, such as the getMethod () method, because getting this method requires traversing all the method lists, including the parent class. If it is not reflection, then the address of this method is determined in advance.
At this point, I believe you have a deeper understanding of the "introduction of common API examples of Java reflection". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.