Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Function Pointer

 
Amit Lonkar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All!!!
In "C" programming, we can have a pointer to a function. Can we have a reference to a function stored in an Object in Java.
Amit
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you looked into reflection?
If you look at the java.lang.Class class, you have use that the find the methods.
Given a method name and the parameter types you can find a particular method and get a java.lang.reflect.Method object which represents the method.
Then you can call invoke() on the Method object and pass it the instance of the class you want to call the method on. You have to pass the parameters that match this method as well.
Hope this gets you started.
Dave
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using reflection is rather complicated. For most problems it is more appropriate to introduce an interface containing the function and having the objects implement that interface.
So instead of passing around function pointers, you pass around function objects. Take a look at Runnable for an example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic