- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 java 8,我想在编译时检测细微的类差异,修改 withProperty()
header 。此代码有效,但我想在 main()
函数中强制出现编译错误,因为 this::getInteger
返回一个整数,第二个参数是一个字符串。
import java.util.function.Function;
public class MatcherProperty<T, K> {
public static <T, K> MatcherProperty<T, K> withProperty(
Function<T, K> mapper,
K expected
){
return new MatcherProperty<>();
}
private Integer getInteger(Object object) {
return 1;
}
public void main() {
withProperty(this::getInteger, "Random string");
}
}
我想避免(如果可能)在 withProperty()
函数中指定类类型或类似内容的第三个参数。也许 K 被翻译成 Object,Integer 和 String 的父类(super class)。引擎盖下到底发生了什么?在这种情况下是否可以强制编译错误?
提前致谢。
最佳答案
您当前代码中没有编译错误,因为调用 withProperty
的结果被忽略。
如果您尝试这样分配结果:
MatcherProperty<Object, Integer> mp = withProperty(this::getInteger, "Random string");
那么你会得到一个编译错误,因为 String
参数与类型不匹配 K
这是 Integer
在结果中。
如果您尝试这样分配结果:
MatcherProperty<Object, String> mp = withProperty(this::getInteger, "Random string");
那么你会得到一个编译错误,因为 Integer
作为第一个参数给出的函数的结果与类型不匹配 K
这是 String
在结果中。
您只能通过使用常见的父类(super class)型(例如 Object
)来编译赋值。或 Serializable
:
MatcherProperty<Object, Serializable> mp = withProperty(this::getInteger, "Random string");
你当然不能强制人们分配结果。您可以添加 Class<K>
参数让他们选择一个类(例如 Integer.class
或 String.class
)但即便如此,他们也可以通过 Serializable.class
或 Object.class
相反:
public static <T, K> MatcherProperty<T, K> withProperty(
Class<K> clazz,
Function<T, K> mapper,
K expected
)
withProperty(String.class, this::getInteger, "Random string"); // doesn't compile
withProperty(Integer.class, this::getInteger, "Random string"); // doesn't compile
withProperty(Serializable.class, this::getInteger, "Random string"); // compiles
如果你不以某种方式告诉编译器什么类型 K
是(使用类参数或类型为 K
的返回值的赋值)然后它将推断通用类型 Serializable
在这种情况下。
关于java - 如何使用泛型(java)在编译时检测类差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62545111/
我是一名优秀的程序员,十分优秀!