首页 技术 正文
技术 2022年11月6日
0 收藏 429 点赞 1,020 浏览 1996 个字
 
public class InvokeTester {
public InvokeTester() {
} String str; public InvokeTester(String str) {
this.str = str;
} public int add(int param1, int param2) {
return param1 + param2;
} public String echo(String msg) {
return "echo: " + msg;
} public String getStr() {
return "one param ctor" + str;
} public static void main(String[] args) throws Exception {
//直接获取类
//Class<?> classType = InvokeTester.class;
//通过完整的类型路径获取类
Class<?> classType = Class.forName("com.top.utils.InvokeTester");
//使用newInstance创建对象
// Object invokeTester = classType.newInstance();
//使用默认构造函数获取对象
Object invokeTester = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//获取InvokeTester类的add()方法
Method addMethod = classType.getMethod("add", new Class[]{int.class, int.class});
//调用invokeTester对象上的add()方法
Object result = addMethod.invoke(invokeTester, new Object[]{new Integer(100), new Integer(200)});
System.out.println((Integer) result);
//获取InvokeTester类的echo()方法
Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
//调用invokeTester对象的echo()方法
result = echoMethod.invoke(invokeTester, new Object[]{"Hello"});
System.out.println((String) result);
//创建有参构造函数的类对象
Object invokeTester1 = classType.getConstructor(new Class[]{String.class}).newInstance(new Object[]{new String("测试一个带参数的构造调用")});
//获取方法方式相同
Method getStrMethod = classType.getMethod("getStr");
Object str = getStrMethod.invoke(invokeTester1);
System.out.println(str);
}
}

 在例程InvokeTester类的main()方法中,运用反射机制调用一个InvokeTester对象的add()和echo()方法 add()方法的两个参数为int 类型,获得表示add()方法的Method对象的代码如下:Method addMethod=classType.getMethod(“add”,new Class[]{int.class,int.class});Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,再将其返回。 在本例中,尽管InvokeTester 类的add()方法的两个参数以及返回值都是int类型,调用add Method 对象的invoke()方法时,只能传递Integer 类型的参数,并且invoke()方法的返回类型也是Integer 类型,Integer 类是int 基本类型的包装类: Object result=addMethod.invoke(invokeTester,new Object[]{new Integer(100),new Integer(200)});System.out.println((Integer)result); //result 为Integer类型  博客搬家了。本文新地址:http://www.zicheng.net/article/3

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905