gpt4 book ai didi

java - 如何使用泛型(java)在编译时检测类差异

转载 作者:行者123 更新时间:2023-12-01 14:31:52 25 4
gpt4 key购买 nike

我正在使用 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.classString.class )但即便如此,他们也可以通过 Serializable.classObject.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/

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