Java从入门到精通 - 反射Method


import java.lang.reflect.Method;

/**
 * @author Administrator  请注意顺序问题
 *
 */
public class MethodTest {

 static void staticMethod()
 {
  System.out.println("执行staticMethod()方法");
 }
 public int publicMethod(int i)
 {
  System.out.println("执行publicMethod()方法");
  return i*20;
 }
 protected int protectedMethod(String s,int  i) throws NumberFormatException{
  System.out.println("执行protectedMethod()方法");
  return Integer.valueOf(s)+i;
 }
 private String privateMethod(String...strings){
  System.out.println("执行privateMethod()方法");
  StringBuffer stringBuffer = new StringBuffer();
  for(int i=0;i<strings.length;i++)
  {
   stringBuffer.append(strings[i]);
  }
  return stringBuffer.toString();
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //实例化一个对象:
  MethodTest methodTest = new MethodTest();
  
  Method[] declaredMethods = MethodTest.class.getDeclaredMethods();  //获得所有的方法
  for(int i=0;i<declaredMethods.length;i++)
  {
   Method method = declaredMethods[i];
   System.out.println("名称:"+method.getName());   //方法名称
   System.out.println("是否允许带有可变参数变量:"+method.isVarArgs());//
   System.out.println("入口参数类型依次为:");
   Class[]parameterTypes = method.getParameterTypes();//获得方法所有的参数类型
   for(int j=0;j<parameterTypes.length;j++)
   {
    System.out.println("parameterTypes[" + j + "]" + parameterTypes[j]);
   }
   System.out.println("返回值类型:"+method.getReturnType()); //获得方法返回值类型
   System.out.println("可能抛出异常类型有:");
   Class []exceptionTypes = method.getExceptionTypes();  //获得可能抛出的所有异常类型
   for(int j=0;j<exceptionTypes.length;j++){
    System.out.println("exceptionTypes[" + j + "]" + exceptionTypes[j]);
   }
   boolean isTurn = true;
   while(isTurn)     //调用类中的方法
   {
    try
    {
     isTurn = false;
        if(i==0)   //请注意生成的顺序,可以先把这些语句注释掉,看下顺序再另行执行。
     {
      method.invoke(methodTest);
     } else if(i==1)
     {
      System.out.println("返回值:" + method.invoke(methodTest,168));
     }else if(i==2)
     {
      System.out.println("返回值:" + method.invoke(methodTest,"7",5));
     }else if(i==3)
     {
      Object[] parameters = new Object[]{new String[]{"M","W","Q"}};
      System.out.println("返回值:"+method.invoke(methodTest, parameters));
     }
    }catch(Exception e)
    {
     System.out.println("在执行方法时抛出异常,执行setAccessible()方法");
     method.setAccessible(true);
     isTurn = true;
    }
   }
   System.out.println("****************");
  }
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值