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

标签 java class generics compilation functional-interface

我正在使用 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/

相关文章:

C#对象复制解释?

c# - 无法使用多个泛型类型获取接口(interface)/类的类型?

Javaagent 路径在 maven/linux/tomcat 上没有得到很好的解释

java - 在 Java 中将 * 打印为三角形?

c++ - 没有在此范围内声明?

C++ 如何显示/打印字符串对象? cout << int 有效,cout << string 无效

c# - 运算符 == 是如何选择的?

c# - 如何在 C# 中使泛型参数 T 可空?

java - 用户使用 openid 登录时获取电子邮件的最佳位置

java - 在 java webmethods 中下载窗口关闭后无法重定向