感谢引入var-args和auto-boxing,Java5彻底的简化了我们对反射的使用。关于var-args的一个有趣的事是:好像没有平台通知我们说,var-args现在是可用的。当然,有一些IDE在pop-up或其他的地方用Object...表识取代了Object[]标识。
但是如果你没有注意到的话,那么这对你是不公平的。看看下面的代码吧,你就会知道我为什么这么说。
package org.javalobby.tnt.vararg;
import java.lang.reflect.Method;
public class TestReflectionExample {
public static void main(String[] args) throws Exception {
String s = "Test String";
preJava5(s);
postJava5(s);
}
private static void preJava5(String s) throws Exception {
// First, do a substring
Class c = s.getClass();
Method m = c.getMethod("substring", new Class[] { int.class, int.class });
Object obj = m.invoke(s, new Object[] { new Integer(0), new Integer(4) });
System.out.println(obj);
// Next, do a 'length'
Method m2 = c.getMethod("length", null);
Integer lengthObj = (Integer)m2.invoke(s, null);
int length = lengthObj.intValue();
System.out.println(length);
}
private static void postJava5(String s) throws Exception {
// First, do a substring
Class<?> c = s.getClass();
Method m = c.getMethod("substring", int.class, int.class);
Object obj = m.invoke(s, 0, 4);
System.out.println(obj);

