Java reflection acquisition method and calling method

Obtaining method in the Class class:

public Method[] getMethods();//Get all public methods including itself and inheritance (implementation)——Method does not support generic <>, that is, it does not follow <>

public Method[] getDeclaredMethods();//Get all its own methods (private, public, protected, regardless of access rights), excluding inherited ones

After jdk1.8, methods that can directly obtain private attributes do not need to set permissions but are limited to the getDeclaredMethod method. For Method methods, still need to be set

authority.

public Method[] getMethod(String methodName, Class<T>...parameterTypes);//Represents obtaining a specified public method, including inherited ones

Parameters: methodName: Indicates the name of the obtained method

       parameterTypes: represents the Class type of the parameters of the obtained method

public Method[] getDeclaredMethod(String methodName, Class<T>...parameterTypes);//Indicates obtaining a specified method (private, protected, public, regardless of access rights) in this class, excluding inherited methods

1. Get a method in a class

public static void main(String args[]) throws Exception {
        Class<?> cls = SysUserClient.class;
//        public Method[] getMethods();//获取包括自身和继承(实现)过来的所有的public方法——Method不支持泛型<>,即后面不接<>
//        public Method[] getDeclaredMethods();//获取自身所有的方法(private、public、protected,和访问权限无关),不包括继承的
        Method methods[] = cls.getDeclaredMethods();
        for (Method met : methods) {
            String res = "";
            int mod = met.getModifiers();
            //先输出方法名字
            res = res + Modifier.toString(mod) + " " + met.getReturnType().getName() + " " + met.getName() +  "(";
            Class<?> params[] = met.getParameterTypes();
            for (int x = 0; x < params.length; x ++) {
                //拼凑出方法要求的数据类型
                res = res + params[x].getName() + " "  + "args-" + x;
                if (x < params.length - 1) {
                    res = res +",";
                }
            }
            res = res + ") ";
            Class<?> exp[] = met.getExceptionTypes();
            if (exp.length > 0) {
                //获取其支持处理的异常信息
                res = res + "throws ";
            }
            for (int x = 0 ; x < exp.length ; x ++) {
                res = res + exp[x].getName();
                if (x < exp.length - 1) {
                    res = res +",";
                }
            }
            System.out.println(res);
            System.out.println(); //换行
        }
    }

Get the result as shown in the figure

 2. Java reflection calling method

//    不使用反射机制怎么调用对象?
//    public static void main(String[] args) {
//        SysUserDTO dto = new SysUserDTO();
//        dto.setUserName("吴素");
//        dto.setId(9);
//        dto.setAge("20");
//        dto.setUserEmail("[email protected]");
//        HopeRequest hopeRequest = new HopeRequest();
//        hopeRequest.setAppId("zkawTest");
//        hopeRequest.setPublicKey(PUBLIC_KEY_STRING);
//        hopeRequest.setType("list");
//        hopeRequest.setData(JSONObject.toJSONString(dto));
//        String pageModelBaseResponse = SysUserClient.invokeApi(hopeRequest);
//        System.out.println(pageModelBaseResponse);
//    }


//通过反射机制调用对象
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        SysUserDTO dto = new SysUserDTO();
        dto.setUserName("吴素");
        dto.setId(9);
        dto.setAge("20");
        dto.setUserEmail("[email protected]");
        HopeRequest hopeRequest = new HopeRequest();
        hopeRequest.setAppId("zkawTest");
        hopeRequest.setPublicKey(PUBLIC_KEY_STRING);
        hopeRequest.setType("list");
        hopeRequest.setData(JSONObject.toJSONString(dto));
        Class clazz  =  SysUserClient.class;
        Method method =  clazz.getDeclaredMethod("invokeApi",new Class[]{HopeRequest.class});
        Object invoke = method.invoke(new SysUserClient(), new Object[]{hopeRequest});
        System.out.println(invoke);
    }

The role of the reflection mechanism: make the code very versatile, and the changeable content is written in the configuration file. After the configuration file is modified in the future, the objects created and the methods called are also different, but the java code does not need to do anything changes.

Replenish:

getMethod(方法名,Object... args)

invoke(Object obj,Object... args)

可变长参数
     Object... args这就是可变长参数
    语法是:类型...(注意:一定是3个点)
    1.可变长参数要求的参数个数是:0~N个
    2.可变长参数只能有一个,并且必须在参数列表的最后一个位置上
    3.可变长数组可以当做一个数组来看待

3. Add some knowledge about Java reflection

The role of Java reflection: When the Java code is compiled, the internal information of the class loaded into the JVM can be accessed through reflection.

Such as: Clazz.getName() to get the full name of the class

                  getPackage() gets the package this class belongs to

                  getSuperclass() Gets the Class object corresponding to the parent class

                   getFiled(String name) Get the specified member variable of the class

                   getMethods() Get the method of the public type of the class

                   getMethod(String name, Class[] args) Get the specified method of the class

Guess you like

Origin blog.csdn.net/askuld/article/details/130879471