Java 8 lambda和带抽象类的接口扩展 [英] Java 8 lambda and extension of interfaces with abstract class

查看:332
本文介绍了Java 8 lambda和带抽象类的接口扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想声明Spring的 RowMapper ,但不是创建动态类,而是实现一个实现RowMapper的抽象类。这是我的方法签名:

Say I want to declare Spring's RowMapper, but not create a dynamic class, but implement an abstract class which implements RowMapper. This is my method signature:

SqlProcedure#declareRowMapper(RowMapper<?> rowMapper);

CustomRowMapper.java:

CustomRowMapper.java:

public abstract class CustomRowMapper<T> implements RowMapper<T> {
    protected A a = new A();
}

旧的Java方式是写:

The old Java way would be to write:

sqlProc.declareRowMapper(new CustomRowMapper<Object>() {
    @Override
    public Object mapRow(ResultSet rs, int rowNum) {
        a.doSomething(rs, rowNum);
        return new Object();
    }
});

是否可以用lambda表达式实现相同的功能?我想做这样的事情:

Is it possible to achieve the same thing with lambda expressions? I would like to do something like this:

sqlProc.declareRowMapper((rs, rowNum) -> {
    a.doSomething(rs, rowNum);
    return new Object();
});

但是我会收到编译错误,说 a无法解决。这是因为Java将此视为 RowMapper#mapRow 方法的实现,而不是 CustomRowMapper#mapRow

But then I would get a compile error saying a cannot be resolved. It's because Java sees this as an implementation of the RowMapper#mapRow method, not CustomRowMapper#mapRow.

如何通过lambda表达式告诉Java使用CustomRowMapper而不是RowMapper?这是否可能?

How do I tell Java to use my CustomRowMapper instead of RowMapper via lambda expressions? Is this even possible?

推荐答案

您可以扩展功能界面并创建自己的界面:

You can extend the functional interface and create one of your own:

@FunctionalInterface
public interface CustomRowMapper<T> implements RowMapper<T> {
    static A a = new A();
}

然后,你可以传递一个lambda,这是<$ c的实现$ c> CustomRowMapper#mapRow()这样的方法:

Then, you can pass a lambda, which is the implementation of CustomRowMapper#mapRow() method like this:

CustomRowMapper myCustomRowMapperLambda = (rs, rowNum) -> {
    a.doSomething(rs, rowNum);
    return new Object();
};
sqlProc.declareRowMapper(myCustomRowMapperLambda);

这篇关于Java 8 lambda和带抽象类的接口扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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