1.对缺乏潜在类型机制的补偿:反射:通国反射能够动态的确定所需要的方法是否可用并调用它们。先创建两个类,都有相同的方法;利用反射调用 ,相同的方法。只能在类与类之间使用。
class A { private int i = 1; public int getI() { return i; } public void setI(int i) { this.i = i; } } class B { private int i = 2; public int getI() { return i; } public void setI(int i) { this.i = i; } } public class Test { public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { A a = new A(); B b = new B(); getI(a); getI(b); } public static void getI(Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> c = o.getClass(); Method method = c.getMethod("getI"); int i = (int) method.invoke(o, null); System.out.println(o.getClass().getSimpleName() + i); } }
2.将一个方法应用于序列:反射提供了潜在类型机制的可能性,但是它将所有类型检查都转移到了运行时。能够实现编译期类型检查,就更好了。将传入的参数变成了迭代器。
class A { private static int i = 1; private final int count = i++; public void getCount() { System.out.println(count); } } public class Test3 { public static <T, S extends Iterable<T>> void test(S s, Method m, Object... o) throws InvocationTargetException, IllegalAccessException { Iterator<T> i = s.iterator(); while (i.hasNext()) { T t = i.next(); m.invoke(t, o); } } public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { ArrayList<A> a = new ArrayList<>(); for (int i = 0; i < 10; i++) { a.add(new A()); } test(a, A.class.getMethod(("getCount"), null)); } }