根据方法名利用反射机制调用该方法 如题,根据方法名利用反射机制调用该方法,但是当该方法有参数,并且参数类型是基本类型比如说int,时如何处理。请举例谢谢 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 看看下面的例子.详细的说明参见下面的网页.http://chenyubo.javaeye.com/blog/552791import java.lang.reflect.Method;public class ReflectTest { public static void main(String[] args) { try { Class cls = Class.forName("Student"); // 不能使用Integer.class代替int.class Method setMethod = cls.getDeclaredMethod("setAge",int.class); setMethod.invoke(cls.newInstance(), 15); Method staticMethod = cls.getDeclaredMethod("hi",int.class,String.class); staticMethod.invoke(cls,20,"chb");//这里不需要newInstance // staticMethod.invoke(cls.newInstance(),20,"chb"); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } }}class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void hi(int age, String name) { System.out.println("大家好,我叫" + name + ",今年" + age + "岁"); }} 还真的不知道int类型也可以用int。class来得到。谢谢啊 问一下java有哪些本地存储数据的方式(交流) 初学者的小问题 关于clone()的问题 重大的事,帮帮助, 把结构体的变量名(上1000个)加入到COMBO BOX 在线求助:java多线程与内存的使用 百分求解困扰我几天的接口引用问题 JTable 的拖拉时的滚动条问题?急!急!急! 测试工具Junit使用。 急!!关于1970年的时间问题!!! 请教一个问题,请进! 大家帮忙看下这道题怎么做?
详细的说明参见下面的网页.
http://chenyubo.javaeye.com/blog/552791import java.lang.reflect.Method;public class ReflectTest { public static void main(String[] args) {
try {
Class cls = Class.forName("Student");
// 不能使用Integer.class代替int.class
Method setMethod = cls.getDeclaredMethod("setAge",int.class);
setMethod.invoke(cls.newInstance(), 15);
Method staticMethod = cls.getDeclaredMethod("hi",int.class,String.class);
staticMethod.invoke(cls,20,"chb");//这里不需要newInstance
// staticMethod.invoke(cls.newInstance(),20,"chb");
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}}class Student {
private int age; private String name; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public static void hi(int age, String name) {
System.out.println("大家好,我叫" + name + ",今年" + age + "岁");
}
}