Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Is there any way to pass a method as the argument of another method in java? Something similar to delegates in C#?

No, Java takes a different approach. The method takes an interface as parameter. The interface is specified to include a certain method.
When you call the method that takes an interface as parameter, you pass an object of a class that implements that interface. This can even be an anonymous class, where you actually implement the method at the point of call.
For example:
interface Foo { void bar(); }
... the method is declared thus:
public void foobar(Foo b) {
b.bar();
}... and you call it like this:
foobar(new Foo() {
public void bar() { System.out.println("Hello world"); }
});

If you are willing/able to extend Java, for example with the JSR241 implementation, you can do this.
An additional possibility is JRuby.
Guy

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |