Java 方法 - 将方法作为参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/887444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:14:28  来源:igfitidea点击:

Java Methods - Taking a method AS AN ARGUMENT

javamethods

提问by Diego

I've come across some code that I can't share here but it declaresa method WITHINthe paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)

我已经遇到了一些代码,我不能分享在这里,但它声明的方法WITHIN另一种方法的放慢参数列表。我什至不知道这是可能的。我真的不明白为什么要这样做。有人可以向我解释一些您作为程序员可能会这样做的用途吗?(注意:由于我无法显示代码,我一般不期望上下文中的解释)

Related:

有关的:

What's the nearest substitute for a function pointer in Java?

Java 中最接近函数指针的替代品是什么?

回答by Dave Webb

Did the code look something like this?

代码看起来像这样吗?

obj.someMethod(myVar,3,new FooObject() {
  public void bar() {
    return "baz";
  }
});

If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner classis being created, and an instance of that class is being passed as the argument.

如果是这样,则该方法不会作为参数传递给另一个方法,而是创建了一个匿名内部类,并且该类的实例作为参数传递。

In the example above FooObjectis an abstract class which doesn't implement the bar()method. Instead of creating a private classthat extends FooObjectwe create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.

在上面的例子中FooObject是一个没有实现bar()方法的抽象类。我们不是创建private class扩展FooObject类,而是创建抽象类的实例,并提供与其余代码一致的抽象方法的实现。

You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous innerclass.

您无法创建抽象类的实例,因此我们必须提供缺少的方法来创建完整的类定义。由于这个新类是动态创建的,它没有名字,因此是匿名的。因为它是在另一个类中定义的,所以它是一个匿名内部类。

It can be a very handy shortcut, especially for Listenerclasses, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.

它可以是一个非常方便的快捷方式,尤其是对于Listener类,但是如果您被带走并且内联方法定义太长,它会使您的代码难以理解。

回答by user15299

In Java you can't pass methods as parameters. Could it have been passing not a method, but an anonymnous inner class?

在 Java 中,您不能将方法作为参数传递。难道它传递的不是方法,而是匿名内部类?

This can be useful for passing behaviours between classes. Google "dependency injection" or "Inversion of control" for more information.

这对于在类之间传递行为很有用。谷歌“依赖注入”或“控制反转”了解更多信息。

回答by paulosuzart

Have you ever seen the Functional Java? It's a very interesting library that allows you programing like you would do in Scala. I Wroteabout this libs. I confess it is better to use in a more flexible syntax (BGGA closures) like Scala.

你见过函数式 Java吗?这是一个非常有趣的库,它允许您像在Scala 中一样进行编程。 我写过这个库。我承认最好使用更灵活的语法(BGGA 闭包),例如 Scala。

Using Functional Java with a high-order function like map on a list we have:

将 Functional Java 与高阶函数(如列表上的 map)一起使用,我们有:

final List<Integer> numbers = list(1, 2, 3, 4, 5);  

List<Integer> c = numbers.map(new F<Integer, Integer>() {  
                 public Integer f(Integer arg) {  
                   return arg * arg;  
                  }  
              });  

Another useful lib is lambdajthat offers nice ways to play like in Functional (FP) Programming. Java has a limited syntax compared to FP languages. But you can still take some advantages of FP style, but you must be creative!

另一个有用的库是lambdaj,它提供了像函数 (FP) 编程一样的好方法。与 FP 语言相比,Java 的语法有限。但是你仍然可以利用 FP 风格的一些优势,但你必须要有创意!

回答by dfa

using java.lang.reflect.Method

使用java.lang.reflect.Method

example

例子

public void callMethod(Method aMethod, int value) throws Exception {
    aMethod.invoke(this, value);
}

public void print(Integer value) {
    System.out.print(value);
}

public void println(Integer value) {
    System.out.println(value);
}

public void demo() throws Exception {
    Method println = this.getClass().getMethod("println", Integer.class);
    Method print = this.getClass().getMethod("print", Integer.class);
    callMethod(println, 10);
    callMethod(print, 10);
}

回答by Apocalisp

The nearest thing to passing a function pointer in Java is passing an anonymous instance of an abstract class or interface. For example, a generic function type can be encoded in an interface like this:

在 Java 中传递函数指针最接近的事情是传递抽象类或接口的匿名实例。例如,通用函数类型可以在这样的接口中编码:

public interface F<A, B> {
  public B f(final A a);
}

You can then expect a method in another method's argument list:

然后,您可以期待另一个方法的参数列表中的方法:

public List<B> map(List<A> as, F<A, B> f) {
  ...
}

And you can call it with an anonymous instance of that interface:

您可以使用该接口的匿名实例调用它:

map(myList, new F<Integer, String>() {
  public String f(Integer i) {
    return String.valueOf(i);
  }
});

There's a library called Functional Javathat exploits exactly this idea for great benefit glorious language Java.

有一个名为Functional Java的库,它正是利用这个想法为光荣的 Java 语言带来了巨大的好处。

回答by Adam Jaskiewicz

You can also do something like this:

你也可以做这样的事情:

final Predicate somePredicate = new Predicate<Item>() 
  {
  @Override
  public boolean apply(Item item)
    {
    return item.someProperty().equals(something);
    }
  }

And use it like this:

并像这样使用它:

List<Item> filteredList = filter(list, somePredicate);

I've done stuff like that before. I've also written methods that use a closure to build and return an anonymous implementation of an interface in a similar way:

我以前做过类似的事情。我还编写了使用闭包以类似方式构建和返回接口的匿名实现的方法:

Predicate isSomeColor(final Color color)
  {
  return new Predicate<Shape>() 
    {
    @Override
    public boolean apply(Shape shape)
      {
      return shape.getColor().equals(color);
      }
    }
  }

List<Shape> redShapes = filter(shapes, isSomeColor(Color.RED);

All of this is still anonymous inner classes. Nowhere am I actually naming the class itself, I just have a reference to an instance of the class.

所有这些仍然是匿名内部类。我实际上没有在任何地方命名类本身,我只有对类实例的引用。

回答by Steve McLeod

It's not, per se, legal syntax in Java. Was it perhaps creating a new instance of an anonymous class?

它本身不是 Java 中的合法语法。可能是创建了一个匿名类的新实例吗?

回答by Amir Arad

this is called reflection. there is a whole library of objects representing stuff like constructors, methods and such.
you can use it, for instance, in order to call a dynamic methodthat is determined on runtime.

这称为反射。有一个完整的对象库,表示构造函数、方法等内容。
例如,您可以使用它来调用在运行时确定的动态方法

回答by Sourabh

Yes, declaration of a method within the parameter list of another method can be done. You can check out java.lang.reflect.Method

是的,可以在另一个方法的参数列表中声明一个方法。你可以查看 java.lang.reflect.Method

Using reflection, you retrieve a Method object representing the method you wish to pass as a parameter. Then you can call Method to invoke to make a call to that method.

使用反射,您可以检索一个 Method 对象,该对象表示您希望作为参数传递的方法。然后您可以调用 Method 来调用该方法。

Moreover, you can refer "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.

此外,您可以参考“Java 语言中的函数式编程”(http://www.ibm.com/developerworks/java/library/j-fp.html),它可以为您提供由内而外的示例。

回答by Diego

The answers above are varying as to whether or not it is even possible. Is it possible through reflection? Is possible through the use of an anonymous inner class? We need to clarify this.

上面的答案对于它是否可能甚至是不同的。是否可以通过反思?是否可以通过使用匿名内部类?我们需要澄清这一点。