mardi 2 août 2016

Verifying if two generic types have the same parameters

Let's say I have this generic class A:

public class A<E> {

    public A(E e) {}

}

How can I know if two instances of this class have the same type parameter, <E>?

I tried this:

public static void main(String[] args) {
    A<String> aString = new A<>("a");
    A<Integer> anInt = new A<>(0);
    System.out.println(aString.getClass().isInstance(anInt));
}

Which outputs true. I guess it makes sense because they have the same class. However if you try doing this:

A<String> anotherString = new A<Integer>(-1);

It will not compile because the type parameters are different. How can I know, at runtime, if two type parameters are different/equivalent? In other words, I need a method that can compare both variables and return false based on their type parameters.





Aucun commentaire:

Enregistrer un commentaire