Is there something equivalent to C function pointers?

T

Todd

Hello,

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
C?

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.

Thanks,
Todd
 
M

Mike Schilling

Todd said:
Hello,

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
C?

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.

http://java.sun.com/docs/white/delegates.html
 
J

Joshua Cranmer

Todd said:
Hello,

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
C?

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.
 
L

Lew

Joshua said:
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.

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top