Java callback methods - java

Can anybody help on how to implement callback methods using annotations in java ?
More detail -
Basically, I have a java method that returns nothing [void] but I wanted it to return the state of the object to the caller without changing the method signature using callback function. Hope that helps.
Thank you!

Very simple.
In some class or interface somewhere you have a method that should be called:
[access modifier] [return type] name([parameter list])...
for instance:
public void callback()
Then in some class you either override that method, or implement it, or something. Then in the code that does the callback you take an argument of the type of the class that has the callback method. For instance:
public interface Callback
{
public void callback();
}
public class Callbackee implements Callback {
public void callback()
{
System.out.println("Hey, you called.");`
}
static{
new Callbackee().doCallback();
}
}
public class CallBacker {
Callback call;
public void registerCallback(Callback call) {
this.call=call;
}
//then just do the callback whenever you want. You can also, of course, use collections to register more than one callback:
public void doCallback() {
call.callback();
}
}
If you want to see examples of callback methods in the Java API, look at MouseListener, MouseMotionListener, KeyListener and so forth. Usually you can register more than one callback of course.

Here is a nice tutorial about that:
http://slesinsky.org/brian/code/annotated_callback.html
Although I'm not sure if this is the thing you're thinking about.

You could wrap your Callback method in an http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.html class, then call ActionListener#actionPerformed(ActionEvent ev)

Related

Java: Is child overriding parent discouraged?

I was wondering if it's frowned upon that when designing an framework to be used by others, a class has some function as default behavior and expects its customers to override it if necessary. An example would be something like the following:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
// process record logic
}
}
Consumers of this library creates their concrete classes to process their own records of type T.
Now I want to add a function called preProcess() to offer the ability for the consumers to preprocess their records. It would then look something like this:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
preprocess();
// process record logic
}
public void preProcess() {
// By default no preprocessing
}
}
I know I can make preProcess an abstract function, but I dont want to due to a couple reasons:
Not all customers need to preprocess their records
We have a pipeline structure that autodeploys pushed code, so making RecordProcessor an abstract class would immediately break our customers' applications.
Is making preProcess do nothing in the parent class and let child classes override it considered bad practice? If not, what should the best way be to let customers know that they now have the power to preprocess the records? Through java docs?
One approach is to mark the public method as final (but this might also break existing apps) and allow protected hook methods to be overridden. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void process() {
doPreProcess();
doProcess();
doPostProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Having some documentation should make it natural for other developers to recognize the optional extension methods.
I don't see anything wrong with having a hook method which does nothing. However, it should contain a return statement so static analysis tools won't complain.
UPDATE: in order to avoid breaking existing apps, if possible mark the existing method as deprecated and introduce a new method. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void execute() {
doPreProcess();
doProcess();
doPostProcess();
}
#Deprecated - use execute() method instead.
public void process() {
doProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Prefer composition over inheritance. If you want your clients to add custom pre processing then do it by delegating to a separate objects.
public interface RecordPreProcessor<T extends Record>{
public void process(T record);
}
public class RecordProcessor<T extends Record> {
private RecordPreProcessor<T> recordPreProcessor = null;
public void setRecordPreProcessor(RecordPreProcessor<T> recordPreProcessor) {
this.recordPreProcessor = recordPreProcessor;
}
public void process() {
if (recordPreProcessor != null) recordPreProcessor.process(record);
// process record logic
}
}
No, overriding is not discouraged in Java.
The language allows overriding.
The language makes all methods overridable by default.
The Java class library includes examples of the same pattern.
Your approach is one reasonable way to allow subclasses to extend the behavior of their parent class. There are alternatives, such as passing a behavior as an object. However, there is no one true way.
One way you could improve your code is to mark preProcess() as protected. It's an implementation detail of the class. You don't want just anyone holding a RecordProcessor to decide they can call preProcess() by itself, right?
public class RecordProcessor<T extends Record> {
...
protected void preProcess() {
^^^^^^^^^
// By default no preprocessing
}
}
Another way to improve this is to consider whether you intend anyone to create an instance of the superclass RecordProcessor. If you don't, make the class abstract, to prevent that. The class name can express that, if you like, or your coding guidelines call for it.
public abstract class AbstractRecordProcessor<T extends Record> {
^^^^^^^^ ^^^^^^^^
...
protected void preProcess() {
// By default no preprocessing
}
}
One common way to document such methods is with the phrase "The default implementation does nothing. Subclasses may override this method ...". For example, below is the documentation for java.util.concurrent.FutureTask.done(). You can find more examples by searching for the first sentence of that phrase online.
public class FutureTask<V> implements RunnableFuture<V> {
...
/**
* Protected method invoked when this task transitions to state
* {#code isDone} (whether normally or via cancellation). The
* default implementation does nothing. Subclasses may override
* this method to invoke completion callbacks or perform
* bookkeeping. Note that you can query status inside the
* implementation of this method to determine whether this task
* has been cancelled.
*/
protected void done() { }
}
What I ended up doing- which I also thought was pretty good, inspired by #tsolakp, was simply creating a child class to RecordProcessor, called something like PreprocessRecordProcessor. This has no way of interfering existing code because nothing existing was touched. The class would something like this:
public class PreprocessRecordProcessor<T extends Record> extends RecordProcessor<T> {
// ...
public void process() {
preProcess();
super.process();
}
protected abstract void preProcess();
}
And if customers of this library would like to add their own logic they can simply extend this class and they'd be forced to provide pre-processing logic (as supposed to having the option to provide, which may result in unexpected results if they forgot to.)

Why interface can be used to get callback on java?

Im using this code on this question :
public void getString(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result=response;
callback.onSuccess(result);
}
}...
}}
public interface VolleyCallback{
void onSuccess(String result);
}
my question is why this interface can be use to listening the response. as i know in java interface is some kind of contract and or some abstract class that has some method. Interface need to be implement before we actually use it but in those code above there are not any implement code....
but the new object based on that interface can be populate as listener. need some concise explanation why this concept happen.
thanks for any explanation.
The interface (Response.Listener<String>) is implemented as an anonymous class instance here :
....
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result=response;
callback.onSuccess(result);
}
}
....
This is equivalent to creating a class that implements Response.Listener<String> and then passing an instance of that class to the StringRequest constructor.
The idea is same as here
public class Button {
private Callback callback;
public Button(Callback callback) {
this.callback = callback;
}
public void update() {
// Check if clicked..
callback.onClick(this);
}
public interface Callback {
public void onClick(Button Button);
}
}
Button b = new Button(new Callback() {
#Override
public void onClick(Button b) {
System.out.println("Clicked");
}
});
In your case StringRequest expects Object that implements method onResponse. Later this method will be callbacked, code body will be executed.
When you send an object you actually send a reference to it. A caller expects possibility to call some methods (it wants you to implement some interface).
This is called the Observer Pattern, or a variation of such, in which you are instantiating a new object that abides the contract of that interface and passing a reference of it to the caller, so it can make use of that object when it's done doing whatever it was doing. It is used because it's practical to define your behaviour in an anonymous class for such an small task.
If you have a lot of repeated behaviour in your callbacks, you could also make a concrete class that implements the callback interface and pass an instance of such to the caller.
When invoking the getString() function you will need to pass in an actual implementation of the interface.
It is also a view :-
Java's object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks.

How to pass a concrete method as parameter to another concrete method

I am newbie to java, and developing a real life project. I have many methods and about 2500 lines of code thus far. Many of the methods are slightly different(usually a difference of mere a single identifier) due to which i have to copy the code again and again with slight changes.
What i want is to pass a method as parameter to another method, I've gone through lambda expressions
but i could not find it enough appealing, off-course due to my own conceptual shortcomings. because it tells to define functional interface of each method to be passed. but as per my thoughts it would not give me a generic code so that i would be able to simply add some other Tables in future.
i am putting a piece of code to demonstrate and better explain my problem.
if(houseTabPanel.getComponentCount()==0){
houseTableDb();
}
if(isSelected){
selection(houseTable);
}
else {
houseTable.setColumnSelectionAllowed(false);
houseTable.setRowSelectionAllowed(false);
houseTable.setCellSelectionEnabled(false);
Rselection(houseTable);
}
now i have different methods named houseTableDb() , plotTableDb() , adminTableDb() etc.
i want to make a method of this piece of code and pass plotTableDb() etc as parameter..
something like...
public void genericMethod(JPanel p, JTable t, some method reference to use instead of houseTableDb){}
pardon me if am not descriptive enough.. any response would be truly appreciated by core of the heart.
Provided that all of these methods have the same signature you can define an interface with a single method with that signature (return value, parameter list). Then you write classes implementing the method, one for each method's implementation. For passing the method, you create an object of that class and pass the object. The call to the actual method is replaced by the call to the method defined in the interface.
interface Callee {
void meth();
}
class MethOne implements Callee {
public void meth(){...}
}
void caller( Callee callee ){
callee.meth();
}
Callee ofOne = new MethOne();
caller( ofOne );
But to avoid all this hazzle: that's why lambdas have been added...
You can do like this :
public void genericMethod(JPanel p, JTable t, TableDbCallBack tableDb)
{
if(p.getComponentCount()==0)
{
tableDb.run();
}
if(isSelected)
{
selection(t);
}
else
{
t.setColumnSelectionAllowed(false);
t.setRowSelectionAllowed(false);
t.setCellSelectionEnabled(false);
Rselection(t);
}
}
usage :
genericMethod(p, t, new HouseTableDb());
genericMethod(p, t, new AdminTableDb());
Implementation :
public interface TableDbCallBack extends Runnable {}
public class HouseTableDb implements TableDbCallBack
{
#Override
public void run()
{
// Whatever it should do
}
}
public class AdminTableDb implements TableDbCallBack
{
#Override
public void run()
{
// Whatever it should do
}
}

Generic callback in Java

What should be the preferable Java interface or similar pattern that could be used as a generic callback mechanism?
For example it could be something like
public interface GenericCallback
{
public String getID();
public void callback(Object notification);
// or public void callback(String id, Object notification);
}
The ID would be needed for cases of overriden hashCode() methods so that the callee identifies the caller.
A pattern like the above is useful for objects that needs to report back to the class they were spawned from a condition (e.g., end of processing).
In this scenario, the "parent" class would use the getID() method of each of these GenericCallback objects to keep a track of them in a Map<String, GenericCallable> and add or remove them according to the notification received.
Also, how should such an interface be actually named?
Many people seem to prefer the Java Observer pattern, but the Observable class defined there is not convenient, since it not an interface to circumvent single inheritance and it carries more functionality than actually needed in the above, simple scenario.
I would genericize the callback, based upon the type of Object passed. This is particularly useful for EventListeners listening for different classes of events. e.g.
public interface Callback<T> {
public void callback(T t);
}
You may be able to use the type T as the key in a Map. Of course, if you want to differentiate between two callbacks that take the same argument, like a String, then you'd need something like your getID().
Here my old blog about using this for Event Listeners The interface Events.Listener corresponds to Callback<T> above. And Broadcasters uses a Map to keep track of multiple listeners based upon the class they accept as the argument.
I'd recommend using Observer pattern since the Observer pattern is the gold standard in decoupling - the separation of objects that depend on each other.
But I'd recommend avoiding using the Java.util.Observable class if you are looking for a generic callback mechanism. Because Observable has a couple of weaknesses: it's not an interface, and forces you to use Object to represent events.
You can define your own event listener like this:
public class MyEvent extends EventObject {
public MyEvent(Object source) {
super(source);
}
}
public interface MyEventListener {
void handleEvent(EventObject event);
}
public class MyEventSource {
private final List<MyEventListener> listeners;
public MyEventSource() {
listeners = new CopyOnWriteArrayList<MyEventListener>();
}
public void addMyEventListener(MyEventListener listener) {
listeners.add(listener);
}
public void removeMyEventListener(MyEventListener listener) {
listeners.remove(listener);
}
void fireEvent() {
MyEvent event = new MyEvent(this);
for (MyEventListener listener : listeners) {
listener.handleEvent(event);
}
}
}
looks like you want to implement the Observer pattern. In this url is a complete implementation for the observer pattern in Java. In your case the observer will be the callback.
Also If you need to implement something more complex, you will end up doing an event/notifier pattern. Take a look at this other pattern here.
Thanks,
#leo.
Callbacks in Java8 can now be done with the java.util.function package.
See Java 8 lambda Void argument for more information.

Why in GWT an interface is instantiated?

Going through this tutorial https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC it is mentioned that to set up a call back Object it is necessary to do the following:
// Set up the callback object.
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
}
public void onSuccess(StockPrice[] result) {
updateTable(result);
}
};
However I noticed AsyncCallback is an interface. As far as I knew interfaces could not be instantiated. How is this possible?
This is an example of using an Anonymous Class to implement a callback in Java. This is equivalent to defining a class that implements that interface. To clarify, this:
new AsyncCallback() {
...
}
is equivalent to this:
public class MyCallback implements AsyncCallback {
...
}
In fact, if you wanted to, you could create your own class in a separate Java file, call it MyCallback, and then do this:
AsyncCallback<StockPrice[]> callback = new MyCallback();
It's all the same.
This is the case of anonymous inner class implementation of that interface.
The demonstrated approach is very frequently used for implementing different listeners and callbacks. More on the topic can be found here.

Categories