Why in GWT an interface is instantiated? - java

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.

Related

Thinking in Java 4th Edition - is it necessary to make a factory for isolating the code from implementation?

I am currently reading "Thinking in Java 4th edition". In the Chapter "Interface" and the sub-chapter "Interfaces and factories", it states the following
An interface is intended to be a gateway to multiple implementations,
and a typical way to produce objects that fit the interface is the
Factory Method design pattern. Instead of calling a constructor
directly, you call a creation method on a factory object which
produces an implementation of the interface—this way, in theory, your
code is completely isolated from the implementation of the interface,
thus making it possible to transparently swap one implementation for
another. Here’s a demonstration showing the structure of the Factory
Method:
(for easy reference, the example codes quoted after my question)
My question is that why don't we just make the "serviceConsumer" method to be like
public static void serviceConsumer(Service s) {
s.method1();
s.method2();
}
In this case, the code depends on the interface "Service" but not the implementation. (It can also "swap" transparently, isn't it?). So, I don't really get to the point of using "factory" here and what it states at start.
-----------------------------below quoted from "Thinking in Java"------------------------------
//: interfaces/Factories.java
import static net.mindview.util.Print.*;
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
class Implementation1 implements Service {
Implementation1() {} // Package access
public void method1() {
print("Implementation1 method1");
}
public void method2() {
print("Implementation1 method2");
}
}
class Implementation1Factory implements ServiceFactory {
public Service getService() {
return new Implementation1();
}
}
class Implementation2 implements Service {
Implementation2() {} // Package access
public void method1() {
print("Implementation2 method1");
}
public void method2() {
print("Implementation2 method2");
}
}
class Implementation2Factory implements ServiceFactory {
public Service getService() {
return new Implementation2();
}
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact) {
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args) {
serviceConsumer(new Implementation1Factory());
// Implementations are completely interchangeable:
serviceConsumer(new Implementation2Factory());
}
}
/* Output:
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2
*/ //:~
Well nothing prevents you from writing such method, the quoted statement is about creation of the object itself.
In this case, the code depends on the interface "Service" but not the implementation
In both cases the code depends on the interface, the difference is, that in your implementation the Service is created outside the method serviceConsumer
Maybe it will be clearer if you see a real use of Factory Method. The TIJ example is without any context.
My favorite example is Collection.iterator(), where Collection is the ServiceFactory and Iterator is the Service. You can see the calls in the serviceConsumer() but think of the following:
Collection c = new ArrayList(); // ArrayList is a Factory for its iterator
Iterator i = c.iterator(); // getService()
if (i.hasNext()) { ...}
If serviceConsumer were a method to print the collection (instead of something without context), you could see how passing an ServiceFactory (ArrayList) is better than passing the Service (Iterator). There is more encapsulation using that (the details of the Service are hidden in the method).
Here are some UML diagrams to help understand the similarities:
Factory method pattern
TIJ Example
Collection.iterator()
Note: The pink classes are actually anonymous classes that implement the Iterator interface type that corresponds to the Collection. They're not normally classes a client will instantiate any other way (hidden).

Need Clarification in Interface concept in JAVA

I am learning Java Programming and I am a beginner. I am learning Interfaces now. I came across the below two simple examples and I have doubt in those
Program1
public interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
// c.nonIfaceMeth();
}
}
Program 2
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Client c = new Client();
c.callback(42);
}
}
Both Program1 and Program2 give the same output.
In Program1, variable c is declared to be of the interface type and in Program2, variable c is declared to be of the Class type.
My doubt is what is the difference between these two programs and what are the advantages of creating a Interface type variable ?
Kindly help me t understand the concept. TIA
I will try to keep it short as web is full explainaions on interfaces.
Interface is a contract. Many classes can implement an interface. Using interface is one way to loosly couple your code components.
In Program1, variable c is declared to be of the interface type
This means that any implementation of this interface can be taken to create a concrete object and your code should not break.
and in Program2, variable c is declared to be of the Class type.
This means that you have to change your code to use right class every time you need to use a different implementation. Your code is very cohesive.
It will make more sense when you start studing things like dependency injection or factory pattern etc. Also helpful in unit testing.
UPDATE
Based on your comment
I want the difference between these two statements "Callback c = new
Client();" and "Client c = new Client();"
It is very conceptual at the moment but Callback c = new Client() but allows you to change the type of your varible Cat any time. Lets say there is an other implementation ImportantClient in your code where interface is used to declare the variable you can at any time change it to c = new ImportantClient(). However you can not do that if you are using Client c = new Client();
Both are same in your case when saying
Client c = new Client();
Here actually you are just creating an object of a client. And calling a method of the class Client.
And when you say
Callback c = new Client();
You are just creating a reference of type CallBack but at runtime an Object of Client is being created. So both are same in your case.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Reference : Oracle JAVA Documentation
Go through : Using an Interface as a Type
One reason to use an interface is when you want to reduce dependencies between classes or components.
If you have a method that can take an interface as a parameter, for example:
public int countItems(List myList) { ... }
... then you are able to pass in any object whose class implements the List interface, without have that dependency hard coded in the method.
In your case, using the interface Callback enables other classes to be used in the code, if they implement the Callback interface.
Another reason is that it buys you flexibility in choice of concrete class. If you create the object and keep a reference to the interface, it restricts you to only interact with the object through the interface's methods. This means that in future, you could change which concrete class you construct, and as long as it implements the interface, your code will continue to work without requiring modification.

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.

Overriding a method in an instantiated Java object

I would like to override a method in an object that's handed to me by a factory that I have little control over.
My specific problem is that I want to override the getInputStream and getOutputStream of a Socket object to perform wire logging.
The generic problem is as follows:
public class Foo {
public Bar doBar() {
// Some activity
}
}
Where I'd like to take an instantiated Foo and replace the doBar with my own that would work as follows:
Bar doBar() {
// My own activity
return original.doBar();
}
For the Socket I'm going to return an InputStream and OutputStream that are wrapped by logging to intercept the data.
Since Java uses class-based OO, this is impossible. What you can do is use the decorator pattern, i.e. write a wrapper for the object that returns the wrapped streams.
I think there is a way to achieve the effect you want. I saw it orriginally used in swing with buttons to allow the programmer to make the button do something when it is clicked.
Say you have your Foo class:
public class Foo {
public Bar doBar() {
// Some activity
}
}
Then you have a runner class or something similar. You can override the doBar() method at the point of instantiation and it will only affect that specific object.
that class may look like this:
public class FooInstance{
Foo F1 = new Foo(){
public Bar doBar(){
//new activity
}
}
Foo F2 = new Foo();
F1.doBar(); //does the new activity
F2.doBar(); //does the original activity found in the class
}
I'm not entirely sure that will do the trick for you but maybe it'll set you in the right direction. If nothing else it is possible to override a method outside of the class, maybe that will help you.
You can't replace methods in existing objects - you can't change an existing object's type, for one thing.
You could create a new instance of another class which delegated to the existing instance, but that has limitations too.
In your real world case is there no way you can simply make a separate call to wrap the streams returned by the socket? Can you give more details.
You can't really change an object on the fly in java.
You could have something which do what you want by wrapping your Foo into another similar objet which will delegate every call to Foo and at the same log everything you want. (see Proxy)
But if you want to do logging, maybe aspect is a better choice. (see AspectJ)
Using a decorator is the right way to go:
Some very similar code to the requirement you have with sockets is here:
http://www.javaspecialists.eu/archive/Issue058.html
Another proxying-related solution: you could use Aspects to override a method on a given object without subclassing it yourself. This is especially appropriate and common for logging. This example uses spring-aop.
class Example {
final Foo foo;
Example(Foo original) {
AspectJProxyFactory factory = new AspectJProxyFactory();
factory.setTarget(original);
factory.addAspect(FooAspect.class);
foo = (Foo) factory.getProxy();
}
#Aspect
static class FooAspect {
#Before("execution(Foo.doBar())")
Object beforeDoBar() {
// My own activity
}
}
If Socket was an interface then you could create a dynamic proxy. Below is an example. I put this here in case other people need to do this and the target instance is an instance of an interface.
The main reason this will not work for Socket is because java.lang.reflect.Proxy.newProxyInstance requires an array of interfaces for its second argument, so classes won't work here. As such for this example I had to create an interface called ParentInterface, which just has the three print methods.
public class Parent implements ParentInterface {
#Override
public void print1() {
System.out.println("parent 1");
}
#Override
public void print2() {
System.out.println("parent 2");
}
#Override
public void print3() {
System.out.println("parent 3");
}
public static void main(String[] args) {
Parent originalInstance = new Parent();
ParentInterface proxied = (ParentInterface) java.lang.reflect.Proxy.newProxyInstance(
Parent.class.getClassLoader(),
new Class[]{ParentInterface.class},
new ParentProxy(originalInstance));
proxied.print1();
proxied.print2();
proxied.print3();
}
static class ParentProxy implements InvocationHandler {
final Object realObject;
public ParentProxy(Object real) {
realObject = real;
}
#Override
public Object invoke(Object target, Method m, Object[] args) throws Throwable {
try {
if (m.getName().equals("print2")) {
print2();
return null;
} else {
return m.invoke(realObject, args);
}
} catch (java.lang.reflect.InvocationTargetException e) {
throw e.getTargetException();
}
}
public void print2() {
System.out.println("wrapper 2");
}
}
}
I'm not sure if this is possible. Have you considered creating your own class, having the object returned by the factory as a member, and then writing the doBar() method for that class.
two options:
easy : if Foo were you implemetn an interface you can use a Dynamic proxy to add new functionality.
more work: what you have is an "around" advice of AOP - you can use any of the existing AOP tools to make that possible. Spring Framework can do it for you, if you are using it already.

Java callback methods

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)

Categories