今天还是挺早来到公司,蒲云没给我安排新任务,就是让我看thinking in java,我看了类型检查那张,一天就这样过去了
package cn.com.agree.test;
/** * 测试反射机制 */
import java.lang.reflect.Method;
public class TestReflect {
int f(Object o) throws Exception { int length = 0; /* 得到类对象 ,并取得方法 */ Class c = o.getClass(); Object oo = c.newInstance(); Method method = c.getMethod("length", new Class[] {int.class }); method.setAccessible(true); Object len = method.invoke(oo, new Object[]{ new Integer(5) });// 利用方法,并调用方法 length = ((Integer)len).intValue();// 软件成整型
return length;
}
static class Test { public int length(int i) { return i * i; } }
public static void main(String[] args) throws Exception {
int len = new TestReflect().f(new Test());
System.out.println(" length长度:" + len); }
}