原文: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,哈,欢迎大家一起探讨。