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.
Edit: Okay, it seems that it might not be possible. I'll try to explain why I wanted to do this in the first place, perhaps there is another way of achieving it. If you wish that I post a diferent question, please let me know.
I have this method:
public void someMethod(A<String> aString) {
System.out.println("I got called!");
}
How can I ensure that the parameter given is actually an A<String>
via reflection?
If I try this:
A<Integer> anInt = new A<>(0);
Method method = Main.class.getMethod("someMethod", anInt.getClass());
method.invoke(new Main(), anInt);
It will still print the "I got called!" message. How can I ensure this won't happen? (If that is possible of course).