在Java8中创建泛型谓词
我对Java 8相当陌生,想知道是否有可能将实例方法传递给另一个方法,而该方法又通过lambda参数调用它: 以这一类为例:在Java8中创建泛型谓词,java,generics,lambda,java-8,predicate,Java,Generics,Lambda,Java 8,Predicate,我对Java 8相当陌生,想知道是否有可能将实例方法传递给另一个方法,而该方法又通过lambda参数调用它: 以这一类为例: import java.util.function.Predicate; public class PredicateTest { private class SomeType { public boolean bar() { return true; } public boolean
import java.util.function.Predicate;
public class PredicateTest {
private class SomeType {
public boolean bar() {
return true;
}
public boolean foo() {
return true;
}
}
public void someMethod() {
Predicate<SomeType> firstPredicate = someType -> someType.bar();
Predicate<SomeType> secondPredicate = someType -> someType.foo();
//...
}
public Predicate<SomeType> getGenericPredicate(/* ?? what goes here ?? */) {
Predicate<SomeType> predicate = someType -> someType./* ?? how to call passed instance method foo or bar? */
return predicate;
}
}
我不知道为什么需要
getGenericPredicate
since而不是
public void someMethodRefactored() {
Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar());
Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo());
//...
}
然后你可以像这样使用它
public void someMethodRefactored() {
Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar);
Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo);
//...
}
public void somemethodrefactured(){
Predicate firstPredicate=getGenericPredicate(SomeType::bar);
谓词secondPredicate=getGenericPredicate(SomeType::foo);
//...
}
我想补充一个简短的解释,实例方法只是一个以对象作为第一个参数的函数,因此它可以像您描述的那样使用。谢谢,我不知道这种语法。@Juergen您想用哪种语法?看起来你知道。如果您不知道公共谓词getGenericPredicate(谓词p){…
中的
,那么您可以在官方通用教程的一部分中阅读更多关于它的内容。
public void someMethodRefactored() {
Predicate<SomeType> firstPredicate = SomeType::bar;
Predicate<SomeType> secondPredicate = SomeType::foo;
//...
}
public <T> Predicate<T> getGenericPredicate(Predicate<T> p) {
//some additional code goes here
return p;
}
public void someMethodRefactored() {
Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar);
Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo);
//...
}