Home  >  Article  >  Java  >  How to obtain methods in Java reflection

How to obtain methods in Java reflection

anonymity
anonymityOriginal
2019-05-08 15:02:064601browse

What is Java’s reflection mechanism?

The JAVA reflection mechanism is in the running state. For any class, all properties and methods of this class can be known; For any object, any method of it can be called. and attributes; This dynamically obtained information and the function of dynamically calling object methods are called the reflection mechanism of the Java language.

To dissect a class, you must first obtain the bytecode file object of the class. The dissection uses the methods in the Class class. Therefore, we must first obtain the Class type object corresponding to each bytecode file.

Reflection is to map various components in the java class into Java Object

For example: a class has: member variables, methods, constructors, packages and other information. Reflection technology can be used to dissect a class and map each component into an object.

The picture shows the normal loading process of a class: the principle of reflection lies in the class object.

Get familiar with loading: The origin of the Class object is to read the class file into memory and create a Class object for it.

How to obtain methods in Java reflection

Three ways to get Class objects

1.1 Object ——> getClass();

1.2 Any data type (including basic data types) has a "static" class attribute

1.3 Through the static method of the Class class: forName (String className) (commonly used)

where 1.1 is Because of the getClass method in the Object class, because all classes inherit the Object class. Thus calling the Object class to get

Example: Calling the method defined by the class through reflection

@Test
    // 通过反射调用类定义的方法
    public void testInvokeMethod() throws Exception {
        Class clazz = Class.forName("java.lang.String");
        // 定义参数类型
        Class[] params = new Class[1];
        params[0] = String.class;
        Method m = clazz.getDeclaredMethod("indexOf", params);
        // 设置参数
        Object[] p = new Object[1];
        p[0] = "e";
        Integer s = (Integer) m.invoke("helloworld!", p);
        System.out.println(s);
    }

The above is the detailed content of How to obtain methods in Java reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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