By performing the method Java reflection

To get information on a dynamic object method, you first need to create a Method type of object or array by one of the following methods.

	getMethods()
	
	getMethods(String name,Class<?> …parameterTypes)
	
	getDeclaredMethods()
	
	getDeclaredMethods(String name,Class<?>...parameterTypes)

The method of access to the specified configuration, it is necessary to access the parameters according to the type of the entry process . For example, accessing a name max, inlet and parameters of type String were int types.

The following can be achieved in two ways:

objectClass.getDeclaredConstructor("max",int.class,String.class);

objectClass.getDeclaredConstructor("max",new Class[]{int.class,String.class});

Method class common method

Static method name Explanation
getName() Gets the name of the method
getParameterType() It returns the various parameters of the method in declaration order in the form of an array type Class
GetReturnType () Return type of the method is obtained in the form of Class objects
getExceptionTypes() This type of method to obtain an exception might be thrown in the form of an array of Class
invoke(Object obj,Object…args) Performing the specified object obj in the method using the args parameter, the return value of type Object
isVarArgs() To see whether the method allows a variable number of parameters, if allowed to return true, false otherwise
getModifiers() Can be obtained by parsing the method uses the integer modifier

Method exemplary method of how to call the class information acquired in the dynamic class method.

1. First create a Book class, and write four methods have different scopes. Book class final code as follows:

public class Book {
    // static 作用域方法
    static void staticMethod() {
        System.out.println("执行staticMethod()方法");
    }

    // public 作用域方法
    public int publicMethod(int i) {
        System.out.println("执行publicMethod()方法");
        return 100 + i;
    }

    // protected 作用域方法
    protected int protectedMethod(String s, int i) throws NumberFormatException {
        System.out.println("执行protectedMethod()方法");
        return Integer.valueOf(s) + i;
    }

    // private 作用域方法
    private String privateMethod(String... strings) {
        System.out.println("执行privateMethod()方法");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < sb.length(); i++) {
            sb.append(strings[i]);
        }
        return sb.toString();
    }
}

2) preparation of test class Test, the class in the main () method to access by all methods reflection Book class, and whether the method with variable type parameter, an output parameter type inlet and the type of information that may be thrown into console.

Test class code as follows:

public class Test {
    public static void main(String[] args) {
        // 获取动态类Book1
        Book book = new Book();
        Class class1 = book.getClass();
        // 获取Book1类的所有方法
        Method[] declaredMethods = class1.getDeclaredMethods();
        for (int i = 0; i < declaredMethods.length; i++) {
            Method method = declaredMethods[i];
            System.out.println("方法名称为:" + method.getName());
            System.out.println("方法是否带有可变数量的参数:" + method.isVarArgs());
            System.out.println("方法的参数类型依次为:");
            // 获取所有参数类型
            Class[] methodType = method.getParameterTypes();
            for (int j = 0; j < methodType.length; j++) {
                System.out.println(" " + methodType[j]);
            }
            // 获取返回值类型
            System.out.println("方法的返回值类型为:" + method.getReturnType());
            System.out.println("方法可能抛出的异常类型有:");
            // 获取所有可能抛出的异常
            Class[] methodExceptions = method.getExceptionTypes();
            for (int j = 0; j < methodExceptions.length; j++) {
                System.out.println(" " + methodExceptions[j]);
            }
            boolean isTurn = true;
            while (isTurn) {
                try { // 如果该成员变量的访问权限为private,则抛出异常
                    isTurn = false;
                    if (method.getName().equals("staticMethod")) { // 调用没有参数的方法
                        method.invoke(book);
                    } else if (method.getName().equals("publicMethod")) { // 调用一个参数的方法
                        System.out.println("publicMethod(10)的返回值为:" + method.invoke(book, 10));
                    } else if (method.getName().equals("protectedMethod")) { // 调用两个参数的方法
                        System.out.println("protectedMethod(\"10\",15)的返回值为:" + method.invoke(book, "10", 15));
                    } else if (method.getName().equals("privateMethod")) { // 调用可变数量参数的方法
                        Object[] parameters = new Object[] { new String[] { "J", "A", "V", "A" } };
                        System.out.println("privateMethod()的返回值为:" + method.invoke(book, parameters));
                    }
                } catch (Exception e) {
                    System.out.println("在设置成员变量值时抛出异常,下面执行setAccessible()方法");
                    method.setAccessible(true); // 设置为允许访问private方法
                    isTurn = true;

                }
            }
            System.out.println("=============================\n");
        }
    }
}

3) run the test class test, followed by a dynamic program will have access to all methods Book class. Access STATICMETHOD running effect () method is as follows:

方法名称为:staticMethod
方法是否带有可变数量的参数:false
方法的参数类型依次为:
方法的返回值类型为:void
方法可能抛出的异常类型有:
执行staticMethod()方法
=============================

Access running effect publicMethod () method is as follows:

方法名称为:publicMethod
方法是否带有可变数量的参数:false
方法的参数类型依次为:
int
方法的返回值类型为:int
方法可能抛出的异常类型有:
执行publicMethod()方法
publicMethod(10)的返回值为:110
=============================

Access running effect protectedMethod () method is as follows:

方法名称为:protectedMethod
方法是否带有可变数量的参数:false
方法的参数类型依次为:
class java.lang.String
int
方法的返回值类型为:int
方法可能抛出的异常类型有:
class java.lang.NumberFormatException
执行protectedMethod()方法
protectedMethod("10",15)的返回值为:25
=============================

Access running effect privateMethod () method is as follows:

方法名称为:privateMethod
方法是否带有可变数量的参数:true
方法的参数类型依次为:
class java.lang.String;
方法的返回值类型为:class java.lang.String
方法可能抛出的异常类型有:
在设置成员变量值时抛出异常,下面执行setAccessible()方法
执行privateMethod()方法
privateMethod()的返回值为:
=============================
发布了457 篇原创文章 · 获赞 94 · 访问量 1万+

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104728415