标签: functional-interface

如果功能接口扩展了另一个接口,它仍然是一个功能接口吗?

Raoul-Gabriel Urma、Mario Fusco 和 Alan Mycroft 在《Java 8 in Action》一书中指出:

public interface Adder{
    int add(int a, int b);
}
public interface SmartAdder extends Adder{
    int add(double a, double b);
}
Run Code Online (Sandbox Code Playgroud)

SmartAdder 不是函数式接口,因为它指定了两个称为 add 的抽象方法(一个是从 Adder 继承的)。

在书中的另一个类似示例中,以下接口称为功能接口。

public interface ActionListener extends EventListener {
     void actionPerformed(ActionEvent e);
}
Run Code Online (Sandbox Code Playgroud)

与第二个示例相比,是什么让第一个示例不是功能接口?

java functional-interface

3
推荐指数
2
解决办法
2513
查看次数

函数式接口egtoString、equals中继承对象类方法有什么用

我找到了以下代码,继承的 equals() 和 toString() 方法的用途是什么。

@FunctionalInterface
public interface  FunInterface<T> {
   // An  abstract method  declared in the functional interface 
   int test(T  o1,   T  o2);

   // Re-declaration of the equals() method in the Object class 
   boolean equals(Object  obj);

   String toString();
}
Run Code Online (Sandbox Code Playgroud)

java inheritance object java-8 functional-interface

3
推荐指数
1
解决办法
320
查看次数

Java 8 函数 - 在执行给定 lambda 之前执行某些操作的“包装器”函数?

我们有以下场景:

测试中,一些上下文变量需要更新。在测试中的确切位置以及确切应该发生的事情是可变的。我想提供一个“包装器”函数,它设置一些上下文变量,然后执行在函数调用中提供给它的所有断言。

因此,类似于以下内容:

public void withDefaultContextA(Function<???, Void> noArgsCall) {

    setupDefaultContextA();
    noArgsCall.invoke() // not sure how apply() would be invoked here
}
Run Code Online (Sandbox Code Playgroud)

或者:

public void withContextA(BiFunction<???, Context, Void> providedContextCall) {

    setupContext(providedContext); // not sure how apply() would be invoked here
}
Run Code Online (Sandbox Code Playgroud)

在相应的测试中,这些应该被调用如下:

@Test
public void testSomething() {

    withDefaultContextA(() -> {
        ... // do some asserts
    }

    withContext((new Context(...)) -> {
        ... // do some asserts
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?可以以这种方式使用 Java 8 函数吗?如果没有,还有另一种方法可以实现这一目标吗?

java java-8 functional-interface

3
推荐指数
1
解决办法
1868
查看次数

如何从作为 lambda 传递的函数接口对象实例获取参数?

@FunctionalInterface
public interface ServiceCaller {
    void callService();
}

//common method to execute any service call
public void executeService(ServiceCaller serviceCaller) {
    //do common things
    //i want to access dbValidationRequest/apiValidationRequest here for logging purpose
    try {
        serviceCaller.callService();
    } catch (Exception ex) {
        //do common things
        LogUtils.log(logger, ex);
    }
    //do common things
}

//my clients call this
public void validateFromDb(DbValidationRequest dbValidationRequest){
    commonUtils.executeService(()-> dbValidationService.validate(dbValidationRequest));
}

//my clients call this
public void validateFromApi(ApiValidationRequest apiValidationRequest){
    commonUtils.executeService(()-> apiValidationService.validate(apiValidationRequest));
}


Run Code Online (Sandbox Code Playgroud)

这是Java Spring应用程序的控制器。在executeService方法中,我传递了ServiceCaller接口的一个实例。我使用此方法从控制器调用所有服务。如果我使用 intelliJ IDEA …

java lambda functional-interface

3
推荐指数
1
解决办法
1319
查看次数

Java:映射将 lambda 存储为值

我想学习 Java 的“新”语法和 API 中的可能性。更新我的意思是 10+(比方说 10-13)。它主要围绕 lambdas 的声明和存储与映射中的值相同的签名的不同实现。最近我主要和 Gosu 一起工作,我可以用这个片段:

var longInput = 10000000L

new LinkedHashMap<String, block(long) : long>( {
    "byte"  -> (\x -> x as byte as long),
    "short" -> (\x -> x as short as long),
    "int"   -> (\x -> x as int as long),
    "long"  -> (\x -> x as long as long)
}).eachKeyAndValue(\key, value ->
  print("${longInput} ${value(longInput) == longInput ? "can" : "cannot"} be converted to ${key}")
)
Run Code Online (Sandbox Code Playgroud)

我可以在 Java 10 中类似地做到这一点:

import java.util.*;

public …
Run Code Online (Sandbox Code Playgroud)

java lambda gosu functional-interface

3
推荐指数
1
解决办法
163
查看次数

从匿名类到 lambda 表达式

当使用下面的匿名类时,我们调用的变量x没有问题

interface Age { 
    int x = 21; 
    void getAge(); 
} 

class AnonymousDemo  { 
    public static void main(String[] args) { 
        Age oj1 = new Age() { 
            @Override
            public void getAge() { 
                // printing age 
                System.out.print("Age is "+x); 
            } 
        }; 
        oj1.getAge(); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

但是当我使用下面的 lambda 表达式相同的代码时,出现了异常:

interface Age { 
    int x = 21; 
    void getAge(); 
} 

class AnonymousDemo { 
    public static void main(String[] args) { 
        Age oj1 = () -> { System.out.print("Age is "+x); };
        oj1.getAge(); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

这里会出现什么问题呢?知道lambda表达式只是实现匿名类的缩写。

java lambda anonymous-class functional-interface

3
推荐指数
1
解决办法
4991
查看次数

Comparator&lt;T&gt; 如何成为函数式接口?

根据功能接口的定义 -功能接口是仅包含一个抽象方法的接口。

但是Comparator<T>有两个抽象方法:

int compare(T o1, T o2);

boolean equals(Object obj);
Run Code Online (Sandbox Code Playgroud)

其他是默认和静态的。

JavaDocs 将其称为功能接口。怎么会这样?

java oop functional-interface

3
推荐指数
1
解决办法
159
查看次数

Java8 中的 BiSupplier

我所看到的BiConsumerBiPredicateBiFunction但不能BiSupplier或类似。我尝试了下面的代码,但有一个异常说:

“在 BiSupplier 中发现的多个非覆盖抽象方法”。

@FunctionalInterface
public interface BiSupplier<T, R> {

    /**
     * Gets a first.
     *
     * @return a first
     */
    T getFirst();


    /**
     * Gets a second.
     *
     * @return a second
     */
    R getSecond();
}
Run Code Online (Sandbox Code Playgroud)

可以请一些人帮我解决这个问题。

java lambda java-8 functional-interface supplier

3
推荐指数
1
解决办法
772
查看次数

Lambda 表达式正确执行,但匿名类定义抛出错误

我想了解Java的Consumer接口。我已经复制了。但是当我用匿名类定义替换 andThen() 方法的返回语句中的 lambda 表达式时,它会抛出 StackOverflowError :

interface Interface<T> {
       
    void accept(T t);

    default Interface<T> andThen(Interface<T> after) {

           //return (T t)->{accept(t); after.accept(t);};//this runs correctly
           
          //below is the anonymous class definition of above lambda expression
          return new Interface<T>(){

            @Override
            public void accept(T t)
            {
                accept(t); //stackoverflow error thrown
                after.accept(t);
            }
          };
     }
}

//Main class:

public class Lambda2 {

    public static void main(String args[]) {
        Interface<String> e1=str -> System.out.println("in e1 - "+str);
    
        Interface<String> e2=str -> System.out.println("in e2 - "+str);
        
        Interface<String> e3 …
Run Code Online (Sandbox Code Playgroud)

java functional-interface

3
推荐指数
1
解决办法
62
查看次数

消除lambda中的功能接口的歧义

假设这个:

ExecutorService service = ...;

// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
Run Code Online (Sandbox Code Playgroud)

lambda表达式默认为Callable.
有没有办法让它实例化Runnable

谢谢你的帮助.

java lambda java-8 functional-interface

2
推荐指数
1
解决办法
216
查看次数