Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit's method count counts compareTo method twice. Why?

I am working on a Java Springframework project and using JUnit4 to test it.

My class implements Comparable and overrides the compareTo method.

In my test, when I do

@Test
Class<myClass> m = myClass.class;
Method[] methods = m.getDeclaredMethods();
assertEquals(5, methods.length); 

This test fails even though there are exactly 5 methods in myClass. When I looked in the Eclipse debugger, I see that the compareTo method gets called twice.

I can't find an explanation for this behavior. Why does this happen?

like image 298
Stealth Avatar asked Jun 05 '26 21:06

Stealth


1 Answers

The compiler generates a bridge method for compareTo()

The mechanism is explained very well in Angelika Langer's Generics FAQ: What is a bridge method?:

What is a bridge method?

A synthetic method that the compiler generates in the course of type erasure. It is sometimes needed when a type extends or implements a parameterized class or interface. The compiler insert bridge methods in subtypes of parameterized supertypes to ensure that subtyping works as expected.

like image 194
Sean Patrick Floyd Avatar answered Jun 08 '26 09:06

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!