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.
Related
While writing spark code, I'm using UDF (user defined function). UDF is an interface and its impelemented in in below way.
package sparkProject;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.api.java.UDF1;
import org.apache.spark.sql.types.DataTypes;
public class UDFfunctions {
public static void registerCountryCodeFunction(SparkSession spark) {
spark.udf().register("registerCountryCodeFunctionUDF", new UDF1<String, Integer>() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Integer call(String t1) throws Exception {
if (t1.toString().toUpperCase().startsWith("I")) {
return 01;
}
return 02;
}
}, DataTypes.IntegerType);
}
}
So UDF1 is an interface and having call method in it. When I create an instance using UDF1 interface, JVM creates Anonymus class which implements UDF1 interface and implements call method too.
In SPARK Api, to use registerCountryCodeFunctionUDF functionality, I need to perform below operation
UDFfunctions.registerCountryCodeFunction(spark);
ds2_populationGt100k_with_ia_filters_only.withColumn("countryCode", callUDF("registerCountryCodeFunctionUDF",ds2_populationGt100k_with_ia_filters_only.col("countryName")));
I want to know, How can I create my own UDF function, where user could register it and then use it in Java ...?
In Simple words, How can I create kind of code in Java where when we call callUDF with required parameters, it calls the functionality which is written Anonymus class..? What needs to written so that when callUDF gets called, it calls the same functionality which is written Anonymus class ?
I hope my question is clear to all..!
Thanks
Whether an object is an instance of anonymous class or not doesn't change anything to how you use it and call its methods.
Your framework simply stores the instances of UDF in a Map somewhere, indexed by the name you provide. And the callUDF() method simply gets it from the Map and invokes its call() method.
Here is a complete example doing the same thing:
// similar to UDF, but not generic to make it easier to understand
interface Callback {
void call(String message);
}
class Registry {
private Map<String, Callback> callbacks = new HashMap<>();
public registerCallback(String name, Callback callback) {
callbacks.put(name, callback;
}
public void invokeCallback(String name, String message) {
Callback cb = map.get(name);
cb.call(message);
}
}
And now you can create Callback instances, using a top-level class implementing the interface, or an anonymous class implementing the interface, or a lambda, register it into the registry, and finally invoke it:
Registry registry = new Registry();
registry.registerCallback("hello", new Callback() {
#Override
void call(String message) {
System.out.println("Hello, here's your message: " + message);
}
});
registry.invokeCallback("hello", "first message");
In the sample code below, I have an interface inside class so that I'm using the methods of interface. But i don't see any effect with/without interface methods. Can someone help me what is the purpose of adding including them?
public class Controller {
FlowerCallBackReceiver mListener;
#Override
public void success(String s, Response response) {
try {
mListener.onFetchProgress(flower);
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
mListener.onFetchComplete();
}
public interface FlowerCallBackReceiver {
void onFetchProgress(Flower flower);
void onFetchComplete();
void onFetchFailed();
}
}
This nested interface declaration is just a simple organizational technique. It won't change the standard Java interface semantics at all.
For instance, developers use it to clean up the top level package namespace. It's a matter a style, one may say.
Some quick Java SE examples:
interface Thread.UncaughtExceptionHandler
interface Map.Entry<K,V>
interface Policy.Parameters
interface DirectoryStream.Filter<T>
interface ServiceRegistry.Filter
etc
There is no obvious reason to have that interface there, based on the code you have shown.
One might typically nest an interface inside a class if implementations of that class are to be used in the body of the rest of the class, for example if Controller had a method like:
void doSomething(FlowerCallBackReceiver callback) {
// ...
}
But this interface isn't used here, so it's not apparent why it would be here.
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.
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)
Given the following Class and Service layer signatures:
public class PersonActionRequest {
PersonVO person
// ... other fields
}
public class MyServiceLayerClass {
public void requestAction(PersonActionRequest request)
{
PersonVO abstractPerson = request.getPerson();
// call appropriate executeAction method based on subclass of PersonVO
}
private void executeAction(PersonVO person) {}
private void executeAction(EmployeeVO employee) {}
private void executeAction(ManagerVO manager) {}
private void executeAction(UnicornWranglerVO unicornWrangler) {}
}
As discussed here, java will select the best method based on type info at compile time. (Ie., it will always select executeAction(PersonVO person) ).
What's the most appropriate way to select the correct method?
The internet tells me that using instanceof gets me slapped. However, I don't see the appropraite way to select the method without explictly casting abstractPerson to one of the other concrete types.
EDIT: To Clarify - The VO passed in is a simple ValueObject exposed for web clients to instantiate and pass in. By convention it doesn't have methods on it, it's simply a data structure with fields.
For this reason, calling personVO.executeAction() is not an option.
Thanks
Marty
If executeAction was a method in a base class or interface that was common to PersonVO, EmployeeVO, ManagerVO and UnicornWranglerVO, you could just call abstractPerson.executeAction() instead of having multiple overridden methods.
Your principle obstacle to polymorphism here seems to be a 'dumb-struct' data object + 'manager class' service non-pattern. The "more polymorphic' approach would be for execute() to be a method that the various person implementations override.
Assuming that can't change, the way you do multiple dispatch in Java is with visitor-looking callbacks.
public interface PersonVisitor {
void executeAction(EmployeeVO employee);
void executeAction(ManagerVO manager);
void executeAction(UnicornWranglerVO unicornWrangler);
}
public abstract class PersonVO {
public abstract void accept(PersonVisitor visitor);
}
public class EmployeeVO extends PersonVO {
#Override
public void accept(PersonVisitor visitor) {
visitor.executeAction(this);
}
}
public class MyServiceLayerClass implements PersonVisitor {
public void requestAction(PersonActionRequest request)
{
PersonVO abstractPerson = request.getPerson();
abstractPerson.accept(this);
}
public void executeAction(EmployeeVO employee) {}
public void executeAction(ManagerVO manager) {}
public void executeAction(UnicornWranglerVO unicornWrangler) {}
}
You could change the way you are approaching the design and use a Visitor, passing the executor into the Person and have the person type determine which to call.
The Visitor pattern is often used to overcome Java lacking double-dispatch.
I would explicitly cast the abstractPerson. Not only does it ensure the JVM gets the right method, it makes it a hell of a lot easier to read and ensure you know what's going on.