我正在开发一个 Java Springframework 项目并使用 JUnit4 对其进行测试。
我的类实现了 Comparable 并覆盖了 compareTo 方法。
在我的测试中,当我这样做的时候
@Test
Class<myClass> m = myClass.class;
Method[] methods = m.getDeclaredMethods();
assertEquals(5, methods.length);
此测试失败即使在 myClass 中恰好有 5 个方法。当我查看 Eclipse 调试器时,我发现 compareTo 方法被调用了两次。
我找不到对此行为的解释。为什么会这样?
最佳答案
编译器为compareTo()
生成桥接方法
机制解释的很好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.
关于java - JUnit 的方法计数对 compareTo 方法计数两次。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294258/