java反射(Reflect)(二)

2014-11-24 09:12:26 · 作者: · 浏览: 4
edMethod("print", String.class);
//调用该方法
method.invoke(clazz.newInstance(), "fancy");
} catch (Exception e) {
e.printStackTrace();
}
}

public void print(int arg){
System.out.println("Arg is int, value is " + arg);
}

public void print(String arg){
System.out.println("Arg is String, value is " + arg);
}
}

后台打印输出结果:


Arg is String, value is fancy

For a simple example:

题:ArrayList list = new ArrayList(); 在这个泛型为 Integer 的 ArrayList 中存放一个 String 类型的对象。

个人分析:泛型的类型检查只存在编译期间,运行期间并不存在泛型类型,可以用反射来实现题设要求


package examination.topic_04;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
* -----------------------------------------
* @描述 测试类
* @作者 fancy
* @邮箱 fancydeepin@yeah.net
* @日期 2012-8-24


* -----------------------------------------
*/
/**
* TOPIC:ArrayList list = new ArrayList(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
*/
public class TestApp {

public static void main(String[] args){

/**
* 泛型的类型检查只存在编译期间,运行期间并不存在泛型类型,可以用反射来实现题设要求
*/
try {
ArrayList list = new ArrayList();
Method add = ArrayList.class.getDeclaredMethod("add", Object.class);
add.invoke(list, "fancy");
System.out.println(list.get(0));
} catch (Exception e) {
e.printStackTrace();
}

}

}

后台打印输出结果:


fancy