I tried to fix a problem with an unknown comparator (without access to the source). So I wrote Reflection Code to find out what types this comparator accepts.
Surprisingly, Reflection tells me that there are two comparison methods: one with a real type and one with an Object:
Comparator<Integer> comp = new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2)
{
return 0;
}
};
Method[] methods = comp.getClass().getMethods();
for (Method method : methods)
{
if(method.getName().equals("compare")){
System.out.println(method);
}
}
Output:
public int de.hinneLinks.stackoverflow.MyClass$1.compare(java.lang.Integer,java.lang.Integer)
public int de.hinneLinks.stackoverflow.MyClass$1.compare(java.lang.Object,java.lang.Object)
Where is this second method comparecoming from?
But you canβt use it, why ?:
comp.compare(1, 2);
comp.compare((Object)1,(Object)2);
However, I can call these methods with Reflection, if I call both methods with new Object(), I will get two different Exceptions:
compare(java.lang.Object,java.lang.Object)
java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer
compare(java.lang.Integer,java.lang.Integer)
java.lang.IllegalArgumentException: argument type mismatch
If you define my comparator with an object, then there is only one method.
source
share