java 类的加载,与获得相应的方法

package com.yxy.core;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import static java.lang.System.out;

/**
 * @author yxy
 * 执行的参数是:类名 方法名
 * java MethodSpy java.lang.Class getConstructor
 *  java MethodSpy java.io.PrintStream format
 *  java MethodSpy java.lang.Class cast
 */
public class MethodSpy {
 //定义输出的格式。
    private static final String  fmt = "%24s: %s%n";

    // for the morbidly curious
    <E extends RuntimeException> void genericThrow() throws E {}

    public static void main(String... args) {
      
 try {
  Class<?> c = null;
   //根据传入的参数加载相应的类
   c = Class.forName(args[0]);
     Method[] allMethods = c.getDeclaredMethods();
     //遍历出加载的类的所有方法。
     for (Method m : allMethods) {
      //如果方法名与输入的参数(方法名)不一致,就跳过当前的循环执行下一次循环。
   if (!m.getName().equals(args[1])) {
       continue;
   }
   //方法名与输入的参数一致,输出方法的相关信息。
  out.format("%s%n", m.toGenericString());//格式化成字符串输出方法相关信息
  out.format(fmt, "ReturnType", m.getReturnType());//返回的类型
  out.format(fmt, "GenericReturnType", m.getGenericReturnType());//原始的返回类型。

  //获取方法的所有的参数的类型。
  Class<?>[] pType  = m.getParameterTypes();
  //获取方法的所有的参数的原始类型。
  Type[] gpType = m.getGenericParameterTypes();
  for (int i = 0; i < pType.length; i++) {
      out.format(fmt,"ParameterType", pType[i]);
      out.format(fmt,"GenericParameterType", gpType[i]);
  }
  //获取方法的异常类型。
  Class<?>[] xType  = m.getExceptionTypes();
  //获取方法原始的异常类型。
  Type[] gxType = m.getGenericExceptionTypes();
  //遍历出所有的异常类型
  for (int i = 0; i < xType.length; i++) {
      out.format(fmt,"ExceptionType", xType[i]);
      out.format(fmt,"GenericExceptionType", gxType[i]);
  }
     }

        // production code should handle these exceptions more gracefully
 } catch (ClassNotFoundException x) {
     x.printStackTrace();
 }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值