Passing a method(reference) to an other method and calling themethod.

Discussion in 'Java' started by Erik, Mar 28, 2008.

  1. Erik

    Erik Guest

    I have a staight forward question. Is is posible to pass a method as a
    parameter and call the passed
    method from within the other method? Something like the apply function
    in Python where can specify which fuction with what parameters is
    called (apply("thisMethod", arg1)).
    The reason I ask this is because I want to implement a callback
    mechanism. How can this be done or is there an other way to implement
    a callback mechanism where it's posible to call an arbitrary method?

    Thanks.

    Erik
    Erik, Mar 28, 2008
    #1
    1. Advertising

  2. Erik

    Jan Thomä Guest

    Re: Passing a method(reference) to an other method and calling the method.

    Erik wrote:

    > I have a staight forward question. Is is posible to pass a method as a
    > parameter and call the passed
    > method from within the other method?


    Straight forward answer - no, not in this way. In dot.net you have a
    delegate language construct, however in Java you can help yourself by
    creating an anonymous class

    interface Callback {
    void callback(Object ... args);
    }


    apply( new Callback() {
    void callback(Object ... args) {
    thisMethod(args[0], args[1]... );
    }
    });


    Not very nice, but i hear closures are to come in one of the next Java
    versions.... You can of course go on reflection or mark callback methods
    with annotations or so but this anonymous class is the "easiest" way to do
    it...

    Jan

    --
    _________________________________________________________________________
    insOMnia - We never sleep...
    http://www.insOMnia-hq.de
    Jan Thomä, Mar 28, 2008
    #2
    1. Advertising

  3. In Java the callback problem are solved passing an Object that hold the
    method.
    Many times these object are created by an anonymous inner class.

    Example API code
    ----------------

    interface Callback {
    void callback();
    }

    void foo(Callback c) {
    // do something
    ...
    // call the callback
    c.callback();
    // do something else
    ...
    }

    Example client code:
    --------------------

    // define callback method
    Callback myCallback = new Callback() {
    public void callback() {
    call the arbitrary method
    }
    };

    // call the library method passing the callback
    foo.callback(myCallback);

    In groovy which is Java based and you can use the closures.

    Alternatively you can use the reflection api which allow you to call a
    method specified my name on a specified Object. I don't know much about
    the reflection api, so I can't provide you an example.


    Erik wrote:
    > I have a staight forward question. Is is posible to pass a method as a
    > parameter and call the passed
    > method from within the other method? Something like the apply function
    > in Python where can specify which fuction with what parameters is
    > called (apply("thisMethod", arg1)).
    > The reason I ask this is because I want to implement a callback
    > mechanism. How can this be done or is there an other way to implement
    > a callback mechanism where it's posible to call an arbitrary method?
    >
    > Thanks.
    >
    > Erik



    --
    Andrea Francia
    http://www.andreafrancia.it/
    Andrea Francia, Mar 28, 2008
    #3
  4. Erik

    Lew Guest

    Jan Thomä wrote:
    > Erik wrote:
    >
    >> I have a staight forward question. Is is posible to pass a method as a
    >> parameter and call the passed
    >> method from within the other method?

    >
    > Straight forward answer - no, not in this way. In dot.net you have a
    > delegate language construct, however in Java you can help yourself by
    > creating an anonymous class
    >
    > interface Callback {
    > void callback(Object ... args);
    > }
    >
    >
    > apply( new Callback() {
    > void callback(Object ... args) {
    > thisMethod(args[0], args[1]... );
    > }
    > });
    >
    >
    > Not very nice, but i hear closures are to come in one of the next Java


    The anonymous (or named - no need to enforce anonymity) class is just fine -
    closures force you to look around for what the closure does. The subclass
    technique delegates the method and shows the logic very nicely.

    I suspect that even if (when?) they introduce closures to Java, I will
    continue to use subtypes anyway, and that the community at large will discover
    that the niftiness of closures during development is outweighed by the
    difficulty during production maintenance.


    --
    Lew
    Lew, Mar 28, 2008
    #4
  5. Erik

    Jan Thomä Guest

    Re: Passing a method(reference) to an other method and calling the method.

    Lew wrote:
    > I suspect that even if (when?) they introduce closures to Java, I will
    > continue to use subtypes anyway, and that the community at large will
    > discover that the niftiness of closures during development is outweighed
    > by the difficulty during production maintenance.



    Well indeed, i find closures a hard to grasp concept. Microsofts delegates
    are much more clear and understandable:

    delegate MyDelegate(String foo, int i);



    public void apply(MyDelegate delegate) {
    delegate("10", 10);
    }


    and for the caller

    void myCallbackFunction(String foo, int i) {
    }


    apply(myCallbackFunction);

    That's quite easy, checked by the compiler and nice to use....

    --
    _________________________________________________________________________
    insOMnia - We never sleep...
    http://www.insOMnia-hq.de
    Jan Thomä, Mar 28, 2008
    #5
  6. Jan Thomä wrote:
    > Lew wrote:
    >> I suspect that even if (when?) they introduce closures to Java, I will
    >> continue to use subtypes anyway, and that the community at large will
    >> discover that the niftiness of closures during development is outweighed
    >> by the difficulty during production maintenance.

    >
    >
    > Well indeed, i find closures a hard to grasp concept. Microsofts delegates
    > are much more clear and understandable:


    I'm finding your example hard to understand, initially at least.

    >
    > delegate MyDelegate(String foo, int i);


    Is "delegate" a keyword here?

    >
    >
    >
    > public void apply(MyDelegate delegate) {


    is "delegate" a parameter name here?

    > delegate("10", 10);
    > }
    >
    >
    > and for the caller
    >
    > void myCallbackFunction(String foo, int i) {
    > }
    >
    >
    > apply(myCallbackFunction);
    >
    > That's quite easy, checked by the compiler and nice to use....
    >


    A couple of thoughts:

    Although I thought they were ugly at first, I've rather got used to
    anonymous/named inner classes for this sort of task.

    I recently saw a video where someone Joshu Bloch commented that adding
    delegates would require large changes to the language for very little
    gain? Possibly http://www.youtube.com/watch?v=ZOwHiGCzZjo

    --
    RGB
    RedGrittyBrick, Mar 28, 2008
    #6
  7. Erik

    Arne Vajhøj Guest

    Jan Thomä wrote:
    > Well indeed, i find closures a hard to grasp concept. Microsofts delegates
    > are much more clear and understandable:
    >
    > delegate MyDelegate(String foo, int i);
    >
    >
    >
    > public void apply(MyDelegate delegate) {
    > delegate("10", 10);
    > }
    >
    >
    > and for the caller
    >
    > void myCallbackFunction(String foo, int i) {
    > }
    >
    > apply(myCallbackFunction);
    >
    > That's quite easy, checked by the compiler and nice to use....


    I agree.

    C# delegates is a very good OO equivalent of a C function pointer.

    Arne
    Arne Vajhøj, Mar 28, 2008
    #7
  8. Erik

    Arne Vajhøj Guest

    RedGrittyBrick wrote:
    > Jan Thomä wrote:
    > I'm finding your example hard to understand, initially at least.
    >> delegate MyDelegate(String foo, int i);

    > Is "delegate" a keyword here?
    >> public void apply(MyDelegate delegate) {

    > is "delegate" a parameter name here?
    >> delegate("10", 10);
    >> }


    delegate is a keyword and the code will not compile as written.

    He meant something like:

    delegate MyDelegate(String foo, int i);

    public void apply(MyDelegate md)
    {
    md("10", 10);
    }

    Arne
    Arne Vajhøj, Mar 28, 2008
    #8
  9. Jan Thomä wrote:
    > apply( new Callback() {
    > void callback(Object ... args) {
    > thisMethod(args[0], args[1]... );
    > }
    > });
    >
    >
    > Not very nice, but i hear closures are to come in one of the next Java
    > versions....


    Not nice? It illustrates what happens quite clearly, IMO, and makes life
    easier for documentation purposes.

    The closures feature is still one in hot debate; the last time I checked
    (admittedly several months ago), there were two or three different,
    non-compatible varieties of closures. It also appears that a majority of
    Java developers are at best indifferent to it or even downright hostile.
    Joshua Bloch (I believe it was him) gave a presentation a few months ago
    as to why he thought that closures were ill-suited to Java, a position
    with which I agree.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Mar 28, 2008
    #9
  10. Erik

    Roedy Green Guest

    Re: Passing a method(reference) to an other method and calling the method.

    On Fri, 28 Mar 2008 02:58:17 -0700 (PDT), Erik <>
    wrote, quoted or indirectly quoted someone who said :

    >I have a staight forward question. Is is posible to pass a method as a
    >parameter and call the passed
    >method from within the other method?


    see http://mindprod.com/jgloss/callback.html
    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
    Roedy Green, Mar 28, 2008
    #10
  11. Erik

    Lew Guest

    Joshua Cranmer wrote:
    > Jan Thomä wrote:
    >> apply( new Callback() {
    >> void callback(Object ... args) {
    >> thisMethod(args[0], args[1]... );
    >> }
    >> });
    >>
    >>
    >> Not very nice, but i hear closures are to come in one of the next Java
    >> versions....

    >
    > Not nice? It illustrates what happens quite clearly, IMO, and makes life
    > easier for documentation purposes.


    Hear, hear! There is a tension between what programmers like to do during
    development, which pushes toward economy of expression, and operational
    concerns, where good logging and readable code are paramount. Anonymous
    classes favor the maintainer, but a few developers tend to whine about them.

    They should spend some time on undocumented code without anyone handy who was
    on its original team.

    > The closures feature is still one in hot debate; the last time I checked
    > (admittedly several months ago), there were two or three different,
    > non-compatible varieties of closures. It also appears that a majority of
    > Java developers are at best indifferent to it or even downright hostile.


    Count me in the latter.

    > Joshua Bloch (I believe it was him) gave a presentation a few months ago
    > as to why he thought that closures were ill-suited to Java, a position
    > with which I agree.


    Years ago Sun put out a white paper about why they chose anonymous classes
    over delegates. It's somewhere on java.sun.com.

    People in these newsgroups have presented quite sharp arguments as to why Sun
    was wrong.

    I do not dislike the delegate idiom - perhaps because I don't use C#. I do
    like the anonymous class idiom, and various other places where Java uses
    subtypes to do what closures or delegates would. Yes, I'm aware that closures
    offer some syntax that inner classes don't, in particular with respect to
    outer object variable visibility. In practice this has never held back the
    effectiveness nor the expressiveness of my Java programs, so far.

    If and when Java sports closures I will try them out. Perhaps they will woo
    me over to the Dark Side.

    --
    Lew
    Lew, Mar 29, 2008
    #11
  12. Erik

    Peter Duniho Guest

    Re: Passing a method(reference) to an other method and calling the method.

    On Fri, 28 Mar 2008 20:58:10 -0700, Lew <> wrote:

    > Joshua Cranmer wrote:
    >> Jan Thomä wrote:
    >>> apply( new Callback() {
    >>> void callback(Object ... args) {
    >>> thisMethod(args[0], args[1]... );
    >>> }
    >>> });
    >>>
    >>>
    >>> Not very nice, but i hear closures are to come in one of the next Java
    >>> versions....

    >> Not nice? It illustrates what happens quite clearly, IMO, and makes
    >> life easier for documentation purposes.

    >
    > Hear, hear! There is a tension between what programmers like to do
    > during development, which pushes toward economy of expression, and
    > operational concerns, where good logging and readable code are
    > paramount. Anonymous classes favor the maintainer, but a few developers
    > tend to whine about them.


    And then...

    > [...]
    > I do not dislike the delegate idiom - perhaps because I don't use C#. I
    > do like the anonymous class idiom, and various other places where Java
    > uses subtypes to do what closures or delegates would.


    It seems to me that you're mixing two different things up (as is Joshua),
    if I read the message correctly.

    I agree that it's nice to have the code that's being "passed" (whether as
    a class implementing an interface or a delegate) present where it's used.
    However, delegates in C# aren't mutually exclusive of that idea.

    An interface implementation versus a delegate discusses _how_ the method
    reference is passed. This is where Java forces the interface
    implementation idiom on you, because it doesn't have a function pointer
    type like delegates.

    An anonymous implementation, whether passed as an interface implementation
    or a delegate, discusses _what_ is passed and _where_ it's declared. This
    is the idiom you appear to be saying you favor, but it's not missing from
    C#.

    C# has anonymous methods and, with C# 3.0, lamba expressions. Two very
    convenient and self-documenting ways to create a delegate instance where
    you need it (just like an anonymous class in Java), providing the all the
    "illustration" and "documentation" advantages of an anonymous class,
    without the disadvantage of having to actually have a whole new class
    (such as some might consider that a disadvantage...I know I do, when the
    class exists solely to contain a method to be called).

    There are occasionally places where I think it'd actually be kind of nice
    to be able to have an anonymous class in C#. It's not that there's
    something wrong with that idea per se. But some times all you really need
    is just one method, and for those situations, delegates work well (and
    IMHO, in those situations they work better than classes, anonymous or
    otherwise).

    > [...]
    > If and when Java sports closures I will try them out. Perhaps they will
    > woo me over to the Dark Side.


    If and when Java does that, I think it will have the best of both worlds.

    Pete
    Peter Duniho, Mar 29, 2008
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. robertm
    Replies:
    1
    Views:
    2,010
    robertm
    Aug 20, 2003
  2. sam pal
    Replies:
    3
    Views:
    525
    E. Robert Tisdale
    Jul 16, 2003
  3. Martin Hess
    Replies:
    4
    Views:
    95
    Martin Hess
    Jun 26, 2009
  4. Iñaki Baz Castillo
    Replies:
    2
    Views:
    212
    Iñaki Baz Castillo
    Apr 20, 2011
  5. Replies:
    2
    Views:
    129
Loading...

Share This Page