Java泛型

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));
    }
}

      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值