[英]How to call methods in functional interfaces without .Method()
public class Main {
public static void main(String[] args) {
MyFunctionalInterface_1 F;
MyFunctionalInterface_2 G;
F = X::Method;
int i = F.Method(5);
System.out.println(i);
G = new X()::Method;
G.Method();
}
}
class X{
public static int Method(double x){
return (int)(x*x*x);
}
public void Method(){
System.out.println("Huy sosi");
}
}
@FunctionalInterface
interface MyFunctionalInterface_1{
int Method(double x);
}
@FunctionalInterface
interface MyFunctionalInterface_2{
void Method();
}
如何将函数称为F()
或G()
?
我在做考试题(翻译自俄语):
在 Java 中编写实体声明 F、G 和 X,以便以下代码片段编译无错误
"F = X::Method; int i = F(0.0); G = new X()::Method; G();"
我不知道我怎么能这样称呼他们。 () 和 (0.0) 或者也许我应该使用不同的东西,而不仅仅是功能接口。 我不是Java专家。 你能帮助我吗?
有可能像这样,利用围绕名称含义的规则:
static int F(double d) {
return 0;
}
static void G() {}
static class X {
void method();
}
public static void main(String[] args) {
Consumer<X> F;
Runnable G;
F = X::Method; int i = F(0.0); G = new X()::Method; G();
}
请注意, F(0.0)
没有调用使用者,并且G()
没有运行可运行对象。 但是,这确实符合“编译无错误”的标准。
经过一番思考,我想出了一种定义它的方法,以便方法调用与函数方法一样:
class X {
static int F(double x) {
return 0;
}
static int Method(double x) {
return F(x);
}
static void G() {}
void Method() {
G();
}
public static void main(String[] args) {
DoubleToIntFunction F;
Runnable G;
F = X::Method; int i = F(0.0); G = new X()::Method; G();
}
}
真是一团糟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.