gpt4 book ai didi

java - 为什么Hamcrest `matches`方法使用Object作为输入类型而不使用泛型类型作为输入

转载 作者:行者123 更新时间:2023-12-02 09:00:40 25 4
gpt4 key购买 nike

我是 Java 新手,正在学习 Hamcrest 框架。

我看了Matcher接口(interface)的代码,看不懂matches(Object actual)的注释和方法签名。我预计它是 matches(T actual) ,并使用泛型类型 T而不是Object它接受一切。

这是源代码: https://github.com/hamcrest/JavaHamcrest/blob/master/hamcrest/src/main/java/org/hamcrest/Matcher.java

对于 matches方法:

public interface Matcher<T> extends SelfDescribing {

/**
* Evaluates the matcher for argument <var>item</var>.
*
* This method matches against Object, instead of the generic type T. This is
* because the caller of the Matcher does not know at runtime what the type is
* (because of type erasure with Java generics). It is down to the implementations
* to check the correct type.
*
* @param actual the object against which the matcher is evaluated.
* @return <code>true</code> if <var>item</var> matches, otherwise <code>false</code>.
*
* @see BaseMatcher
*/
boolean matches(Object actual);

阅读该方法上面的注释,表明这是故意的,我不明白为什么。我知道什么是java中的类型删除。但我仍然不明白为什么 Hamcrest 的设计者认为最好使用对象作为输入,而不是声明为泛型的接口(interface)的泛型类型 public interface Matcher<T> extends SelfDescribing

最佳答案

问:

I don't understand why.

答:(来自 JavaDocs)

This is because the caller of the Matcher does not know at runtime what the type is (because of type erasure with Java generics). It is down to the implementations to check the correct type.

同样来自 JavaDocs:

When using Hamcrest, there is no guarantee as to how often matches() or describeMismatch() will be called

您必须查看 Hamcrest-Libs 实现。
因此,您的 matches() 实现由 Hamcrest (使用任何对象)内部调用。在运行时,Hamcrest 没有机会知道(并找到!)正确的 matches(...) 方法,因为泛型已被清除。您需要检查自己,(由 Hamcrest)传递的对象是否确实匹配。这和Hamcrest没有太大关系。

干杯!

关于java - 为什么Hamcrest `matches`方法使用Object作为输入类型而不使用泛型类型作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60184724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com