将方法保存到变量java 8中 [英] Save a method into a variable, java 8
问题描述
是否可以将方法保存到变量中?
我有一个名为MyFilter的类,它在不同的字段上过滤项目。
MyFilter的构造函数应该询问2件事:
Is it possible to save a method into a variable?
I have a class which is called MyFilter and it filters Items on different fields.
The constructor of MyFilter should ask 2 things:
- 字符串,例如按语言过滤项目,英语
- 这应该是一种方法
例如:
我有一个项目和我想检查语言==字符串是否给过滤器
所以我需要得到该项的语言,所以Item.getLanguage()...
我还需要它适用于Item.getTitle(),Item.getId()等。
I have an Item and I want to check if the language == String given to the filter
So I need to get the language of that Item, so Item.getLanguage()...
I also need it for Item.getTitle(), Item.getId() and so on.
我认为这可能与lambda有关,但我不知道如何。
I think this is possible with lambda's but I don't know how.
推荐答案
是的,您可以对任何方法进行变量引用。对于简单的方法,通常使用 java.util.function。
类就足够了。对于复杂方法,您必须使用此方法定义 @FunctionalInterface
。以下是工作示例:
Yes, you can have a variable reference to any method. For simple methods it's usually enough to use java.util.function.
classes. For complex methods you have to define your @FunctionalInterface
with this method. Here's working example:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
final Consumer<Integer> simpleReference = Main::someMethod;
simpleReference.accept(1);
simpleReference.accept(2);
simpleReference.accept(3);
final ComplexInterface complexReference = Main::complexMethod;
final String complexResult = complexReference.someMethod("888", 321, new ArrayList<>());
System.out.println(complexResult);
}
private static void someMethod(int value) {
System.out.println(value);
}
private static String complexMethod(String stringValue, int intValue, List<Long> longList) {
final StringBuilder builder = new StringBuilder();
builder.append(stringValue).append(" : ").append(intValue);
for (Long longValue : longList) {
builder.append(longValue);
}
return builder.toString();
}
@FunctionalInterface
public static interface ComplexInterface{
String someMethod(String stringValue, int intValue, List<Long> longList);
}
}
这篇关于将方法保存到变量java 8中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!