Is there a way to pass a call back function in a Java method?
The behavior I'm trying to mimic is a .Net Delegate being passed to a function.
I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
A little nitpicking:
Passing a callback includes creating a separate object in pretty much any OO language, so it can hardly be considered overkill. What you probably mean is that in Java, it requires you to create a separate class, which is more verbose (and more resource-intensive) than in languages with explicit first-class functions or closures. However, anonymous classes at least reduce the verbosity and can be used inline.
I've recently started doing something like this:
Basically if you want to make the object of an interface it is not possible, because interface cannot have objects.
The option is to let some class implement the interface and then call that function using the object of that class. But this approach is really verbose.
Alternatively, write new HelloWorld() (*oberserve this is an interface not a class) and then follow it up with the defination of the interface methods itself. (*This defination is in reality the anonymous class). Then you get the object reference through which you can call the method itself.
You also can do the
Callback
using theDelegate
pattern:Callback.java
PagerActivity.java
CustomPagerAdapter.java
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.
This is very easy in Java 8 with lambdas.