Benchmarking compares methods with reflection

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); //Compiles
comp.compare((Object)1,(Object)2); //Does not Compile

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.

+4
source share
2 answers

(compare(Object obj1, Object2) - , :

, , , , . , , .

, , :

for (Method method : methods) {
    if (method.getName().equals("compare") && !method.isBridge()) {
        System.out.println(method);
    }
}
+6

Type Erasure, ( ) Generics Java.

Java , , Object, .

JVM Java-5, Comparator<Integer> , Comparator ( compare(Object, Object)). compare(Object, Object) Integer compare(Integer, Integer), .

+3

Source: https://habr.com/ru/post/1615113/


All Articles