反射_获取当前运行时类的方法结构

package com.zhou.java2;

import com.zhou.java1.Person;
import org.junit.jupiter.api.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 获取当前运行时类的方法结构
 *
 * @author upzhou
 * @create 2022-04-02 15:09
 */
public class MethodTest {

    @Test
    public void test1(){
        Class clazz = Person.class;

        //getMethods(): 获取当前运行时类及其所有父类中声明为 public 权限的方法
        Method[] methods = clazz.getMethods();
        for (Method m : methods){
            System.out.println(m);
        }
        System.out.println();

        //getDeclaredMethods(): 获取当前运行时类中声明的所以方法(不包含父类中声明的方法)
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : declaredMethods){
            System.out.println(m);
        }
    }

    /*
    @Xxx
    权限修饰符  返回值类型  方法名(参数类型1 形参名1, ...) throws XxxException{}
     */
    @Test
    public void test2(){
        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : declaredMethods){
            //1.获取声明的注解
            for (Annotation a : m.getAnnotations()) {
                System.out.println(a);
            }
            //2. 权限修饰符
            System.out.println(Modifier.toString(m.getModifiers()) + "\t");

            //3.返回值类型
            System.out.println(m.getReturnType().getName() + "\t");

            //4.方法名
            System.out.println(m.getName() );
            System.out.print("(");
            //5.形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if (!(parameterTypes == null && parameterTypes.length == 0)){
                for (int i = 0; i < parameterTypes.length; i++){

                    if (i == parameterTypes.length - 1){
                        System.out.print(parameterTypes[i].getName() + "args_" + i);
                        break;
                    }
                    System.out.print(parameterTypes[i].getName() + "args_" + i + ",");
                }
            }
            System.out.print(")");

            System.out.println();

        }
    }

}

 

posted @ 2022-04-30 15:13  UpZhou  阅读(38)  评论(0)    收藏  举报