java精髓_java从入门到精髓 - 反射Method

importjava.lang.reflect.Method;/***@authorAdministrator

**/publicclassMethodTest {staticvoidstaticMethod()

{

System.out.println("执行staticMethod()方法");

}publicintpublicMethod(inti)

{

System.out.println("执行publicMethod()方法");returni*20;

}protectedintprotectedMethod(String s,inti)throwsNumberFormatException{

System.out.println("执行protectedMethod()方法");returnInteger.valueOf(s)+i;

}privateString privateMethod(String...strings){

System.out.println("执行privateMethod()方法");

StringBuffer stringBuffer=newStringBuffer();for(inti=0;i

{

stringBuffer.append(strings[i]);

}returnstringBuffer.toString();

}/***@paramargs*/publicstaticvoidmain(String[] args) {//TODO Auto-generated method stub//实例化一个对象:MethodTest methodTest=newMethodTest();

Method[] declaredMethods=MethodTest.class.getDeclaredMethods();//获得所有的方法for(inti=0;i

{

Method method=declaredMethods[i];

System.out.println("名称:"+method.getName());//方法名称System.out.println("是否允许带有可变参数变量:"+method.isVarArgs());//System.out.println("入口参数类型依次为:");

Class[]parameterTypes=method.getParameterTypes();//获得方法所有的参数类型for(intj=0;j

{

System.out.println("parameterTypes["+j+"]"+parameterTypes[j]);

}

System.out.println("返回值类型:"+method.getReturnType());//获得方法返回值类型System.out.println("可能抛出异常类型有:");

Class []exceptionTypes=method.getExceptionTypes();//获得可能抛出的所有异常类型for(intj=0;j

System.out.println("exceptionTypes["+j+"]"+exceptionTypes[j]);

}booleanisTurn=true;while(isTurn)//调用类中的方法{try{

isTurn=false;if(i==0)//请注意生成的顺序,可以先把这些语句注释掉,看下顺序再另行执行。{

method.invoke(methodTest);

}elseif(i==1)

{

System.out.println("返回值:"+method.invoke(methodTest,168));

}elseif(i==2)

{

System.out.println("返回值:"+method.invoke(methodTest,"7",5));

}elseif(i==3)

{

Object[] parameters=newObject[]{newString[]{"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、付费专栏及课程。

余额充值