Java反射与泛型的本质

来源:互联网 发布:用php写一个 编辑:程序博客网 时间:2024/05/18 13:44

下面是一个获取类方法的反射

<span style="font-size:18px;">import java.lang.reflect.Method;public class GetClassDemo {public static void main(String[] args) {printClassInfo("123");}public static void printClassInfo(Object obj){Method[] methods=(obj.getClass()).getMethods();for (Method method : methods) {System.out.print(method.getReturnType().getName()+" ");System.out.print(method.getName()+" "+"(");for (Class c : method.getParameterTypes()) {System.out.print(c.getName()+",");}System.out.println(")");}}}</span>

通过反射理解泛型的本质

import java.lang.reflect.Method;import java.util.ArrayList;public class SetArrayList {// 泛型中的反射,向String列表中添加Int型public static void SetArrayListOtherParmer() throws Exception {ArrayList<String> strings = new ArrayList<>();strings.add("sada");Class c = strings.getClass();/* * 第一个参数为方法名,第二个参数为参数类类型, * 泛型限制为String,只是为了编译之前的约束,以免出错 * 运行时ArrayList中不再限制为String,即回到了Object */Method m = c.getMethod("add",Object.class);m.invoke(strings, 100);for (Object obj : strings) {System.out.println(obj);}}public static void main(String[] args) throws Exception {SetArrayListOtherParmer();}}



0 0