Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of the principle of Java reflection Mechanism

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points about the example analysis of the principle of Java reflection mechanism. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

What is a reflex?

The reflection mechanism is in the running state, which provides Java with the ability of "operating objects". In the running state, through the Class file object, you can call properties, methods, and constructors in any class, including private ones, and all classes are transparent in front of the reflection mechanism.

Own summary: you can see everything in this class through the Class file object, and you can use and modify it.

The premise of reflection is to get the Class file object (bytecode object), then there are three ways to get it:

Class.forName ("full class name")-through the static method of the Class class (most commonly used)

Class name .class

Object .getClass ()

/ / method 1: get bytecode object, Class.forName ("full class name") Class cla1 = Class.forName ("Study01.Person"); / / method 2: class name .ClassClass cla2 = Person.class;// mode 3: object .getClass (); Person per = new Person (); Class cla3 = per.getClass () / / all three class objects are generated by the class Person / / so let's see if the three bytecode objects are the same: System.out.println (cla1==cla2); System.out.println (cla2==cla3)

/ / output result: two true

Conclusion:

A bytecode object is generated when the class is loaded, and there is only one

No matter which way to get the bytecode object is the same bytecode object

Get the properties in the class through reflection:

After getting the Class bytecode object, we can get the properties, methods, constructors, and private decorations of the class we want through the bytecode object.

Partial Class method:

Demo demo:

1. Create a Person class with two public and two private properties (do not set the construction and get/set, just see if the reflection can get the value)

Public class Person {private String name; / / name private int age = 18; / / Age public int ID = 123; / / ID card public String Sex; / / gender @ Override public String toString () {return "name" + name+ "Age:" + age+ "ID:" + ID+ "gender:" + Sex;}}

Test class:

Public class Test {public static void main (String [] args) throws ClassNotFoundException {/ / get the Class file object, using the most commonly used static method Class per = Class.forName ("Test01.Person") through the Class class; / / here is the incoming full path! Start with the outermost package name! / / use the getFields () method to get all the properties modified by public (screenshot above) / / and return an array of type Field Field fields [] = per.getFields (); for (Field field:fields) {System.out.println (field);}

Output:

We have successfully obtained all the public attributes in the Person class

2. You can also get all the properties, including private ones: (other code will not be rewritten)

For (Field field: per.getDeclaredFields ()) {System.out.println (field);}

Output:

3. Get the public attribute and modify this value:

Field f = per.getField ("Sex"); System.out.println (f); / / get an object: Object obj = per.getConstructor (). NewInstance (); / / modify value: f.set (obj, "male"); Person p = (Person) obj; System.out.println (p.Sex)

Output:

4. Get the private attribute and modify this value: here, connect the above values that modify the public attribute:

Person p = (Person) obj; / / get the public field and call it, and modify Field f = per.getField ("Sex"); / / get an object: Object obj = per.getConstructor (). NewInstance (); f.set (obj, "male") / / modify the Sex attribute to a male / / call private attribute, and modify f = per.getDeclaredField ("name"); / / before accessing the value of the private attribute, set to run the access ↓ / / ignore the access check before access, called brute force reflection f.setAccessible (true); f.set (obj, "Zhang San") System.out.println ("the message in Person is:" + p.toString ());}}

Output:

Get the methods in the class (public, private, construct) through reflection:

Person class:

Public class Person {private String name; / / name private int age = 18; / / Age public int ID = 123; / / ID card public String Sex; / / gender / / structure: public Person () {} public Person (String name, int age, int ID, String sex) {this.name = name; this.age = age; this.ID = ID; Sex = sex Public method: public void eat () {System.out.println ("I will eat");} / / Public method: public void eat (String food) {System.out.println ("I'm eating:" + food);} / / participation and method private void play (String name) {System.out.println (name+ "playing") }}

Test class:

Public class Test {public static void main (String [] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {/ / get the public method in Person and parent Object: System.out.println ("- get public method ↓ in Person and parent Object -"); for (Method method: Person.class.getMethods ()) {System.out.println (method) System.out.println ("method name:" + method.getName ());} / / get the methods in Person, including private System.out.println ("- methods obtained in Person, including private ↓ -"); for (Method method:Person.class.getDeclaredMethods ()) {System.out.println (method.getName () + "") } / / get the eat method in Person according to the method name: System.out.println ("- get the eat method ↓ -" in the Person class based on the method name); Method earMethod1 = Person.class.getMethod ("eat"); Person per = new Person (); / / through invoke (Object,param...) To call the specified method earMethod1.invoke (per); / / call the parametric method using reflection; System.out.println ("- call the parametric method (passed in parameter) ↓ -" using reflection); Method earMethod2 = Person.class.getMethod ("eat", String.class); earMethod2.invoke (per, "beef") / / obtain private play methods through brute force reflection: System.out.println ("- obtain private play method input parameters through brute force reflection) ↓ -"); Method earMethod3 = Person.class.getDeclaredMethod ("play", String.class); / / set run access earMethod3.setAccessible (true) before accessing methods of private properties EarMethod3.invoke (per, Xiao Wang);}

Output:

-get the public method ↓ in Person and parent class Object-

Public void Test02.Person.eat (java.lang.String)

Method name: eat

Public void Test02.Person.eat ()

Method name: eat

Public final void java.lang.Object.wait () throws java.lang.InterruptedException

Method name: wait

Public final void java.lang.Object.wait (long,int) throws java.lang.InterruptedException

Method name: wait

Public final native void java.lang.Object.wait (long) throws java.lang.InterruptedException

Method name: wait

Public boolean java.lang.Object.equals (java.lang.Object)

Method name: equals

Public java.lang.String java.lang.Object.toString ()

Method name: toString

Public native int java.lang.Object.hashCode ()

Method name: hashCode

Public final native java.lang.Class java.lang.Object.getClass ()

Method name: getClass

Public final native void java.lang.Object.notify ()

Method name: notify

Public final native void java.lang.Object.notifyAll ()

Method name: notifyAll

These are all the contents of the article "example Analysis of the principle of Java reflection Mechanism". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report