• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing a method to a method  RSS feed

 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Might be a dumb question but is there an easy way to pass a reference to a method to a method?

I have a test method and I want to compare how it behaves when calling either methodA or methodB (both of which obviously are interchangeable with the same return types and arguments).

I could just copy and paste the test method and do a find/replace on the called method names, but is there a better way?
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way to do this is by inheritance and run-time polymorphism. Example:
Another way is via reflection, but its better not to mess with that.
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interfaces are more common than abstract classes, but that's basically the way to do it in Java. Just check out interfaces like ActionListener, MouseListener, etc.
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, this approach did cross my mind - I'll give it a go, using interfaces.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!