提取Java中两个不同类的泛型函数 [英] Extract generic Function for two different classes in java

查看:72
本文介绍了提取Java中两个不同类的泛型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个switch语句,它具有完全相同的功能代码,重复了两次,我想将其干燥:

I have this switch statement that has the exact same function code repeated twice and I would like to DRY it up:

case "form" -> handleProvider.withHandle(handle -> handle.attach(FormDao.class).findFormById(id))
        .thenApply(form -> { // Form.class
            if (form == null) throw exceptionIfNotFound;
            return form;
        })
        .thenApply(obj -> obj.exportedDocument);
case "note" -> handleProvider.withHandle(handle -> handle.attach(NoteDao.class).findNoteById(id))
        .thenApply(note -> { // Note.class
            if (note == null) throw exceptionIfNotFound;
            return note;
        })

如果IntelliJ提取了我得到的公用位

If IntelliJ extract the common bits I get

            final Function<Form,Form> formFormFunction = form -> {
                if (form == null) throw exceptionIfNotFound;
                return form;
            };

显然仅适用于一个代码路径; Form 对象,但不是 Note 对象.这两个对象实际上并没有在此实现相同的接口,但是,另一方面,我没有在代码中使用任何特定的接口.我只想说我有一个方法接受a并输出一个不变的值,并且T可以是任何值.

which obviously just works for one code path; the Form objects, but not the Note objects. The two objects do not actually implement the same interface here, but on the other hand, I do not make use of any specific interface in the code. I just want to say I have a method that takes a and outputs a unchanged, and that T could be anything.

推荐答案

将其放入方法而不是变量中.这样,您就可以使其通用.

Make this into a method rather than a variable. This way you can make it generic.

private static <T> Function<T, T> getNullCheckFunction() {
    return t -> {
        if (form == null) throw exceptionIfNotFound;
        return t;
    };
}

然后您可以执行以下操作:

Then you can do:

case "form" -> handleProvider.withHandle(handle -> handle.attach(FormDao.class).findFormById(id))
        .thenApply(getNullCheckFunction()) // here!
        .thenApply(obj -> obj.exportedDocument);
case "note" -> handleProvider.withHandle(handle -> handle.attach(NoteDao.class).findNoteById(id))
        .thenApply(getNullCheckFunction()) // here!

请注意,您在 getNullCheckFunction 返回的函数中所做的工作与 Objects.requireNonNull 非常相似.如果您可以抛出 NullPointerException 而不是自己的异常,则可以执行以下操作:

Note that what you are doing in the function returned by getNullCheckFunction is very similar to Objects.requireNonNull. If you are fine with throwing NullPointerException instead of your own exception, you can just do:

.thenApply(Objects::requireNonNull)

这篇关于提取Java中两个不同类的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆