首页 > 其他分享 >获取方法和调用方法

获取方法和调用方法

时间:2022-10-23 17:12:40浏览次数:52  
标签:调用 work System 获取 println cls 方法 Method out

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);
    }
}

 

标签:调用,work,System,获取,println,cls,方法,Method,out
From: https://www.cnblogs.com/jeldp/p/16818906.html

相关文章