Is there something equivalent to C function pointers?

Discussion in 'Java' started by Todd, Aug 9, 2007.

  1. Todd

    Todd Guest


    Is there a way to pass a reference of a method (method object?) to a
    second method analagous to the way one could pass function pointers in

    I would like to be able to not have to define a new abstract class
    with abstract methods that I place within a concrete method so that
    the methods are called appropriately.

    If it's not possible, so be it. However, if you have ideas better
    than an new abstract class, I would love to hear them.

    Todd, Aug 9, 2007
    1. Advertisements

  2. Todd

    Roedy Green Guest

    Is there a way to pass a reference of a method (method object?) to a
    Roedy Green, Aug 9, 2007
    1. Advertisements

  3. No. The Java way to do this is to pass an object that implements some
    interface known to the called method. This object is often an instance of
    an inner (and in particular anonymous) class. if you're interested, here's
    a white paper from Sun explaining why they prefer inner classes to method
    pointers as a callback mechanism.
    Mike Schilling, Aug 9, 2007
  4. It is possible (but not recommended) to pass a java.lang.reflect.Method
    object, which is the closest you can get. However, using an interface or
    abstract class is faster, more maintainable, and probably ultimately
    clearer even than function pointers.
    Joshua Cranmer, Aug 9, 2007
  5. Todd

    Lew Guest

    Java is Java. It's not C, it's not C++, and it's not C#. One difference is
    that Java does not expose "method pointers" (more formally, "closures").

    There is a groundswell of support for closures in Java and I believe it's
    under consideration. Personally I am dubious of the idiom, being perfectly
    satisfied with polymorphism and functors. That likely means I'll be the most
    rabid convert to closures when I finally grok them.
    Lew, Aug 9, 2007
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.