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 Application method of Java reflection

2025-03-29 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 of case analysis of Java reflection. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Reflection definition

The object can get its class through reflection, and the class can get all the methods (including private ones) through reflection. Through the reflection mechanism in the java language, it can manipulate bytecode files, and can read and modify bytecode files.

The basic use of reflection 1. Get the class object A. forName () method

You only need to know the class name, and the instance code will be used when loading JDBC

Public class test1 {public static void main (String [] args) throws ClassNotFoundException {Class name = Class.forName ("java.lang.Runtime"); System.out.println (name);}}

b. Direct acquisition

Use .class to get the object for

Public class test1 {public static void main (String [] args) throws ClassNotFoundException {Class name = Runtime.class; System.out.println (name);} c. GetClass () method

GetClass to get the bytecode object, you must specify the specific class, and then create the object

Public class test1 {public static void main (String [] args) throws ClassNotFoundException {Runtime rt = Runtime.getRuntime (); Class name = rt.getClass (); System.out.println (name);} d. GetSystemClassLoader () .loadClass () method

This method is similar to forName, as long as it has a class name, but the difference is that the static JVM of forName loads the class and executes the code in static ()

Public class getSystemClassLoader {public static void main (String [] args) throws ClassNotFoundException {Class name = ClassLoader.getSystemClassLoader () .loadClass ("java.lang.Runtime"); System.out.println (name);}} 2. Get the class method a. GetDeclaredMethods

Returns all methods declared by a class or interface, including public, protected, private, and default methods, but excluding inherited methods

Import java.lang.reflect.Method;public class getDeclaredMethods {public static void main (String [] args) throws ClassNotFoundException {Class name = Class.forName ("java.lang.Runtime"); System.out.println (name); Method [] m = name.getDeclaredMethods (); for (Method xpurm) System.out.println (x);}}

B. GetDeclaredMethod

To get a specific method, the first parameter is the method name, and the second parameter is the class object corresponding to the method parameter. For example, here the exec method parameter of Runtime is a String, so the second parameter here is String.class.

Import java.lang.reflect.Method;public class getDeclaredMethod {public static void main (String [] args) throws ClassNotFoundException, NoSuchMethodException {Class name = Class.forName ("java.lang.Runtime"); Method m = name.getDeclaredMethod ("exec", String.class); System.out.println (m);} c. GetMethods

Returns all the public methods of a class, including the public methods of the inherited class

D. GetMethod

Parameter isomorphism getDeclaredMethod

3. Get member variables

In the same way, Method's methods

A. GetDeclaredFields

Gets an array of all variables for the members of the class, but not the parent class

B. GetDeclaredField (String name)

Gets a specific parameter that is the name of the desired method

C. GetFields ()

Similarly, you can only get public's, but include the parent's

D. GetField (String name)

Similarly, the parameter is the name of the desired method

4. Get the constructor Constructor

Constructor [] getConstructors (): returns only the public constructor

Constructor [] getDeclaredConstructors (): returns all constructors

Constructor getConstructor (class... ParameterTypes): match the public constructor that matches the parameter matching

Constructor getDeclaredConstructor (class... ParameterTypes): a constructor that matches the parameter matching

The parameters of the last two methods are class objects of type for the parameters of the method, similar to the one of Method, such as String.class

5. Reflection creates a class object newInstance

You can generate instantiated objects through reflection. Generally, we use the newInstance () method of the Class object to create class objects.

The creation method is as follows: you only need to create the newInstance method in the class object obtained by the forname method.

Class c = Class.forName ("com.reflect.MethodTest"); / / create Class object Object M1 = c.newInstance (); / / create class object invoke

The invoke method is located in the java.lang.reflect.Method class and is used to execute the target method of an object, which is usually called in conjunction with the getMethod method.

Usage:

Public Object invoke (Object obj, Object... Args)

The first parameter is the instance of the class, and the second parameter is the parameter in the corresponding function.

Obj: the object from which the underlying method is called, must be an instantiated object

Args: for method calls, it is an array of object with possibly multiple arguments

It is important to note, however, that the first parameter of the invoke method is not fixed:

If calling this method is a normal method, the first parameter is the class object

If the calling method is static, the first parameter is the class

To understand through an example

Import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Invoke {public static void main (String [] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {Class c = Class.forName ("Invoke"); Object o = c.newInstance (); Method m = c.getMethod ("test"); m.invoke (o);} public void test () {System.out.println ("Test successful") }}

In a nutshell, that's it.

Method .invoke (class or class object)

First forName gets the Class, then newInstance gets the class object, then getMethod gets the method, and then calls

Rce example of Runtime (access restriction Breakthrough)

There is an exec method in the Runtime class that executes commands

Import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Exec {public static void main (String [] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {Class c = Class.forName ("java.lang.Runtime"); Object o = c.newInstance (); Method m = c.getMethod ("exec", String.class); m.invoke (o, "/ System/Applications/Calculator.app/Contents/MacOS/Calculator");}}

But found that the report was wrong.

The reason for this problem is:

The class used has no parameter constructor

The class constructor used is private

So the solution is setAccessible (true); use this to break access restrictions.

The Java.lang.reflect.AccessibleObject class is the base class for Field,Method and Constructor classes and can provide the ability to mark reflective objects as using it to suppress Java access control checking, while the Field,Method and Constructor in the above reflective classes inherit from AccessibleObject. So we call the setAccessible () method based on these class methods, which can operate on these private fields.

To put it simply, private properties, methods, and constructors can be used to break through the restrictions. Xxx.setAccessible (true) can see that the constructor of Runtime is private.

So here we can break through the restrictions, first get the constructor, then setAccessible get access, and then finally in invoke, the first parameter is written as con.newInstance ()

Import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Exec {public static void main (String [] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {Class c = Class.forName ("java.lang.Runtime"); Constructor con = c.getDeclaredConstructor (); con.setAccessible (true); Method m = c.getMethod ("exec", String.class) M.invoke (con.newInstance (), "/ System/Applications/Calculator.app/Contents/MacOS/Calculator");}}

There is a doubt here. If the con.newInstance is extracted separately, it will not be displayed when he opens the calculator, but the background does start. I don't know why.

Import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Exec {public static void main (String [] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {Class c = Class.forName ("java.lang.Runtime"); Constructor con = c.getDeclaredConstructor (); con.setAccessible (true); Object o = con.newInstance (); Method m = c.getMethod ("exec", String.class) M.invoke (o, "/ System/Applications/Calculator.app/Contents/MacOS/Calculator");}} postscript

Several important methods commonly used in reflection:

Get the method of class: forName

The method of instantiating class objects: newInstance

How to get the function: getMethod

The method of holding the function: invoke

Limitation Breakthrough method: setAccessible

These are all the contents of the article "case Analysis of the Application of Java reflection". 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: 268

*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