Table of Contents
Reflection
Reflection definition
Basic application of reflection
1. Obtain class objects
a. forName() method
b. Get it directly
c. getClass() method
d. getSystemClassLoader().loadClass() method
2. Get the class method
a. getDeclaredMethods
b. getDeclaredMethod
c. getMethods
d. getMethod
3. Get member variables
a. getDeclaredFields
b . getDeclaredField(String name)
c. getFields()
d. getField(String name)
4. Get the constructor Constructor
5. Create class objects by reflection
newInstance
后记
Home Java javaTutorial How to use Java reflection and analysis of examples

How to use Java reflection and analysis of examples

May 06, 2023 pm 04:31 PM
java

    Reflection

    Reflection definition

    The object can obtain its class through reflection, and the class can obtain all methods (including Private) Through the reflection mechanism in the java language, bytecode files can be operated, and bytecode files can be read and modified.

    Basic application of reflection

    1. Obtain class objects

    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);
        }
    }
    Copy after login

    How to use Java reflection and analysis of examples

    b. Get it directly

    Use .class to get the object

    public class test1 {
        public static void main(String[] args) throws ClassNotFoundException {
            Class<?> name = Runtime.class;
            System.out.println(name);
        }
    }
    Copy after login
    c. getClass() method

    getClass to get the bytecode object, you must be clear about 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);
        }
    }
    Copy after login
    d. getSystemClassLoader().loadClass() method

    This method is similar to forName, as long as there is a class name, but the difference is that the static JVM of forName The class will be loaded and the code in static() will be executed

    public class getSystemClassLoader {
        public static void main(String[] args) throws ClassNotFoundException {
            Class<?> name = ClassLoader.getSystemClassLoader().loadClass("java.lang.Runtime");
            System.out.println(name);
        }
    }
    Copy after login

    2. Get the class method

    a. getDeclaredMethods

    Returns all methods declared by the class or interface, including public , protected, private and default methods, but does not include 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 x:m)
                System.out.println(x);
        }
    }
    Copy after login

    How to use Java reflection and analysis of examples

    b. getDeclaredMethod

    Gets a specific method, the first parameter is the method name. The second parameter is the class object corresponding to the parameter of the method. For example, the exec method parameter of Runtime here 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);
        }
    }
    Copy after login
    c. getMethods

    Return all public methods of a class, including public methods of inherited classes

    d. getMethod

    The parameters are the same as getDeclaredMethod

    3. Get member variables

    Similar to the methods of Method

    a. getDeclaredFields

    Gets all variable arrays of members of the class, but does not include those of the parent class

    b . getDeclaredField(String name)

    Get specific, the parameter is the name of the desired method

    c. getFields()

    Similarly, you can only get public, But it includes the parent class

    d. getField(String name)

    Similarly, the parameter is the name of the desired method

    4. Get the constructor Constructor

    Constructor[] getConstructors(): Returns only public constructors

    Constructor[] getDeclaredConstructors(): Returns all constructors

    Constructor<> getConstructor(class... parameterTypes): matches the public constructor that matches the parameter type

    Constructor<> getDeclaredConstructor(class... parameterTypes ): Match the constructor that matches the parameter type

    The parameters of the latter two methods are class objects of the type of the method parameters, similar to the one of Method, for example String.class

    5. Create class objects by reflection

    newInstance

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

    The method of creation is: you only need to create the newInstance method in the class object obtained through the forname method

    Class c = Class.forName("com.reflect.MethodTest"); // 创建Class对象
    Object m1 =  c.newInstance(); // 创建类对象
    Copy after login

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

    Usage:

    public Object invoke(Object obj, Object... args)
    Copy after login

    The first parameter is the instance of the class, 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: used for method invocation, is an array of objects, the parameters may be multiple

    , but it should be noted that the first parameter of the invoke method does not It is not fixed:

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

    • If calling this method is static Method, the first parameter is the class;

    Through an example to understand

    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("测试成功");
        }
    }
    Copy after login

    How to use Java reflection and analysis of examples

    This is it in simple terms

    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

    Runtime rce example (access restriction breakthrough)

    There is an exec method in the Runtime class, which can execute the command

    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");
        }
    }
    Copy after login

    But it was found that an error was reported

    How to use Java reflection and analysis of examples

    The reason for this problem:

    • The class used does not have a parameterless constructor

    • The class constructor used is private

    Then the solution is

    setAccessible(true);, use this to break through access restrictions

    Java.lang.reflect.AccessibleObject类是Field,Method和Constructor类对象的基类,可以提供将反射对象标记为使用它抑制摸人Java访问控制检查的功能,同时上述的反射类中的Field,Method和Constructor继承自AccessibleObject。所以我们在这些类方法基础上调用setAccessible()方法,既可对这些私有字段进行操作

    简单来说,私有的属性、方法、构造方法,可以通过这个去突破限制,xxx.setAccessible(true) 可以看到Runtime的构造方法是private的

    How to use Java reflection and analysis of examples

    那么这里我们就可以这么去突破限制 先获取构造方法,然后setAccessible获取访问权限 然后再最后invoke里面,第一个参数写成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");
        }
    }
    Copy after login

    How to use Java reflection and analysis of examples

    这里有一个疑问,如果把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);
            Object o = con.newInstance();
            Method m = c.getMethod("exec",String.class);
            m.invoke(o,"/System/Applications/Calculator.app/Contents/MacOS/Calculator");
        }
    }
    Copy after login

    后记

    反射中常用的几个重要方法:

    • 获取类的⽅法: forName

    • 实例化类对象的⽅法: newInstance

    • 获取函数的⽅法: getMethod

    • 执⾏函数的⽅法: invoke

    • 限制突破方法:setAccessible

    The above is the detailed content of How to use Java reflection and analysis of examples. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

    Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

    See all articles