获取方法和调用方法

复制代码
package com.liu.test03;

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

/**
 * @author : liu
 * 日期:16:22:11
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Test03 {
    //这是一个main方法:是程序的入口
    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取字节码信息
        Class cls = Student.class;
        //获取方法
        //getMethods获取运行时类的方法还有所有父类中的方法(被Pbulic修饰的)
        Method[] methods = cls.getMethods();
        for (Method m:methods
             ) {
            System.out.println(m);
        }
        System.out.println("-------------------");
        //getDeclaredMethods获取运行时类中所有的方法
        Method[] declaredMethods = cls.getDeclaredMethods();
        for (Method m:declaredMethods
             ) {
            System.out.println(m);
        }
        System.out.println("===================");
        //获取指定方法
        Method showInfo = cls.getMethod("showInfo");
        System.out.println(showInfo);
        Method showInfo1 = cls.getMethod("showInfo", int.class, int.class);
        System.out.println(showInfo1);
        Method work = cls.getDeclaredMethod("work",int.class);
        System.out.println(work);
        System.out.println("====================");
        //获取方法的具体结构
        /*
        @注解
        修饰符 返回值类型 方法名(参数列表)throws  xxxx{}
         */
        //名字:
        System.out.println(work.getName());
        //修饰符
        int modifiers = work.getModifiers();
        System.out.println(Modifier.toString(modifiers));
        //返回值
        System.out.println(work.getReturnType());
        //参数列表
        for (Class<?> parameterType : work.getParameterTypes()) {
            System.out.println(parameterType);
        }
        System.out.println("===================");
        Method myMethod = cls.getMethod("myMethod");
        Annotation[] annotations = myMethod.getAnnotations();
        //利用foreach遍历数组
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //获取异常
        Class[] exceptionTypes = myMethod.getExceptionTypes();
        for (Class c:exceptionTypes
             ) {
            System.out.println(c);
        }
        //调用方法:
        Object o = cls.newInstance();
        Object invoke = myMethod.invoke(o);
        Object invoke1 = showInfo1.invoke(o, 12, 45);
        System.out.println(invoke1);
    }
}
复制代码

 

posted @   爱的加勒比  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示