@FunctionalInterface是必须的吗

发布时间 2023-07-25 15:37:42作者: IT知识生产小店铺

我的疑惑来源于源码中的函数式接口没有加@FunctionalInterface也可以支持lambda表达式

例如RedisTemplate的源码:

@Override
    public Boolean expire(K key, final long timeout, final TimeUnit unit) {

        byte[] rawKey = rawKey(key);
        long rawTimeout = TimeoutUtils.toMillis(timeout, unit);

        return execute(connection -> {
            try {
                return connection.pExpire(rawKey, rawTimeout);
            } catch (Exception e) {
                // Driver may not support pExpire or we may be running on Redis 2.4
                return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit));
            }
        }, true);
    }

execute的第一个参数使用了lambda表达式,而第一个参数却没有声明@FunctionalInterface:

    @Nullable
    public <T> T execute(RedisCallback<T> action, boolean exposeConnection) {
        return execute(action, exposeConnection, false);
    }
/**
 * Callback interface for Redis 'low level' code. To be used with {@link RedisTemplate} execution methods, often as
 * anonymous classes within a method implementation. Usually, used for chaining several operations together (
 * {@code get/set/trim etc...}.
 *
 * @author Costin Leau
 */
public interface RedisCallback<T> {

    /**
     * Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or
     * closing the connection or handling exceptions.
     *
     * @param connection active Redis connection
     * @return a result object or {@code null} if none
     * @throws DataAccessException
     */
    @Nullable
    T doInRedis(RedisConnection connection) throws DataAccessException;
}

bing搜索了一下: