Java反射机制 Java反射机制的作用,还有就是动态语言就是程序运行时,允许改变程序结构或变量类型。我不是很理解 什么叫做在运行时允许改变????? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 你可以写在文件中:Class.forName("从文件中读取").newInstance; 平时写程序,创建对象的时候就用new,你程序new多少个就创建多少个对象。但是现在要创建不定数量或不定类型的对象,只能用反射机制了。。 public class Test { private Test() { } public int add(int param1, int param2) { return param1 + param2; } public String echo(String msg) { return "echo:" + msg; } public static void main(String[] args) throws Exception { Class classType = Test.class; Object invokeTester = classType.newInstance(); // 调用InvokeTester对象的add()方法 Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class }); 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 }); result = echoMethod.invoke(invokeTester, new Object[] { "Hello" }); System.out.println((String) result); }}这个Test不能被new ,但是通过反射,调用了他的方法 急,高分求解一个从数据库取浮点数据的问题 求助一个数据库字段的设计,请教如何【注解】此字段 ldap 用户验证失败,在线等急急急!!! 找数字 关于图片路径问题 struts2 的 map支持!!高手帮忙 请问jboss怎么配置jndi绑定一个普通对象? look for the expert in java JSP的实验室管理系统开发求帮助 springboot配置tomcat启动报错org.apache.catalina.LifecycleException: Failed to start 发送email问题 怎么学习项目流程?
但是现在要创建不定数量或不定类型的对象,只能用反射机制了。。
private Test() {
} public int add(int param1, int param2) {
return param1 + param2;
} public String echo(String msg) {
return "echo:" + msg;
} public static void main(String[] args) throws Exception {
Class classType = Test.class;
Object invokeTester = classType.newInstance();
// 调用InvokeTester对象的add()方法
Method addMethod = classType.getMethod("add", new Class[] { int.class,
int.class });
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 });
result = echoMethod.invoke(invokeTester, new Object[] { "Hello" });
System.out.println((String) result);
}
}
这个Test不能被new ,但是通过反射,调用了他的方法