JAVA反射系列之Method,java.lang.reflect.Method的使用

原文:http://my.oschina.net/u/1407116/blog/209417

最近写项目,用反射的比较多,写一个总结,以便查阅。

  Method是反射最基本的一个类。

  直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
  * @ClassName: Test
  * @Description: 测试类
  * @author JoseanLuo  
  * @date 2014-3-16 下午8:47:46
  * @version V1.0 
  */
public  class  Test {
     
    public  String doRun(String pk,Student stu,String testrun)
    {
        return  pk+stu+testrun;
    }
}

 测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import  java.lang.reflect.Method;
/**
  * @ClassName: ReflectMethodTest
  * @Description: 反射方法测试
  * @author JoseanLuo  
  * @date 2014-3-18 下午8:53:51
  * @version V1.0 
  */
public  class  ReflectMethodTest
{
public  static  void  main(String[] args)  throws  Exception
{
Class clz=Class.forName( "com.cx.test.Test" );
System.out.println(clz);
Test test=(Test) clz.newInstance();
Method mt=clz.getMethod( "doRun" new  Class[]{String. class ,Student. class ,String. class });
System.out.println(mt);
System.out.println(mt.invoke(test,  new  Object[]{ "i love you " , null , "i fuck you" ,}));
}
}

忘记加student类了,看我别一篇文章吧。

想要调用一个类的方法。

首先要获得这个类Class

这里用的

?
1
Class.forName( "com.cx.test.Test" );

取得clz,

然后利用clz.

?
1
clz.getMethod( "doRun" new  Class[]{String. class ,Student. class ,String. class });

取得Method对象

这里后一个可以不传,此时调用的是名字的无参方法。如

?
1
clz.getMethod( "doRun" );

调用的是doRun()方法。

如果你要想获取的方法和你传的参数类型,个数不同就会出错(排除重载)

得到了你相要的方法对象之后。

你就能直接调用他了

?
1
mt.invoke(test,  new  Object[]{ "i love you " , null , "i fuck you" ,})

注意:方法参数顺序,按方法接收参数顺序。

赶紧试一下吧。 想要更加高级的功能,多看API,哈,欢迎大家一起探讨。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值