Computing.Net > Forums > Programming > Pass method as parameter, Java

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Pass method as parameter, Java

Reply to Message Icon

Name: hjg10
Date: January 18, 2008 at 00:59:00 Pacific
OS: WinXP professional
CPU/Ram: Intel E2160, 1GB
Comment:

Is there any way to pass a method as the argument of another method in java? Something similar to delegates in C#?



Sponsored Link
Ads by Google

Response Number 1
Name: klint
Date: January 18, 2008 at 01:46:40 Pacific
Reply:

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"); }
});


0

Response Number 2
Name: Guy
Date: January 18, 2008 at 15:26:34 Pacific
Reply:

If you are willing/able to extend Java, for example with the JSR241 implementation, you can do this.

An additional possibility is JRuby.

Guy


0

Response Number 3
Name: hjg10
Date: January 18, 2008 at 17:29:23 Pacific
Reply:

Thanks, I will try that out.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Pass method as parameter, Java

Move files with date as parameter www.computing.net/answers/programming/move-files-with-date-as-parameter/16606.html

Method as param to unknown object? www.computing.net/answers/programming/method-as-param-to-unknown-object/17004.html

So confused about C functions.. www.computing.net/answers/programming/so-confused-about-c-functions/7040.html