package cn.com.agree.test;
/** * 测试反射机制 目的是通过反射机制来得到目的类中的属性,来操作相关内容. * 首先我通过反射,得到类对象Class c = o.getClass(); * 然后得到该类的指定名的方法length,通过Class的方法 * public Method getMethod(String name, * Class... parameterTypes) * throws NoSuchMethodException, * SecurityException * 来操作,其中类中方法参数放在了一个类数组里 new Class[]{int.class} * 其中,我对int.class不太理解,不是用 类名.class 来创建一个类对象吗?是不是基本数据类型可以这么直接创建啊.它和Integer.class的区别是什么? * 还有就是那个访问权限的问题.我把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();//实例化传进来的类
/* * getMethod参数是按声明顺序标识该方法形式参数类型的 Class 对象的一个数组。 如果 parameterTypes 为 * null,则按空数组处理。 */
Method method = c.getMethod("length", new Class[] { int.class }); Object obj = method.invoke(oo, new Object[] { new Integer(5) });// 利用方法,并调用方法
length = ((Integer) obj).intValue();// 转成整型
return length; }
// 测试类 static class Test { public int length(int i) { return i * i; } }
static class Test2 { private int rate; public Test2(int rate) { this.rate = rate; }
public int length(int i) { return i * rate; } }
public static void main(String[] args) throws Exception {
int len = new TestReflect().f(new Test2(15)); // int len = new TestReflect().f("hello");
System.out.println(" length长度:" + len); }
}
这是经理给我安排的任务,就是通过反射机制,找出一个未知方法的length方法,并打印出.我用了一天半的时间才弄对它.真是有点担心弄不出来.不过终于还是弄好了.这是我到公司的第二个星期.