//调用该方法
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
个人分析:泛型的类型检查只存在编译期间,运行期间并不存在泛型类型,可以用反射来实现题设要求
package examination.topic_04;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* -----------------------------------------
* @描述 测试类
* @作者 fancy
* @邮箱 fancydeepin@yeah.net
* @日期 2012-8-24
* -----------------------------------------
*/
/**
* TOPIC:ArrayList
*/
public class TestApp {
public static void main(String[] args){
/**
* 泛型的类型检查只存在编译期间,运行期间并不存在泛型类型,可以用反射来实现题设要求
*/
try {
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