Java Delegate Interface - java

Is there a simple Interface in Java like the following code?
public interface Delegate {
void action();
}
Java Delegates? describes the functionality well.
It's not a Supplier, not a Consumer, not a Function, not a Runnable(no async stuff needed), I just want to pass a lambda to a method to be executed in between common parts.
Now I'm wondering why I have to define this interface myself. Am I just unable to find the standard Java interface for this or am I missing some vital drawback here?
Usage in my code (simplified):
public void transferX(Xrequest request){
transfer(request, () -> this.typedWrite(request));
}
public void transferY(Yrequest request){
transfer(request, () -> this.typedWrite(request));
}
void transfer(BaseRequest request, final Delegate writeFunction){
...
try{
writeFunction.action();
...
catch(...){...}
}
void typedWrite(Xrequest request){...}
void typedWrite(Yrequest request){...}

OK, as Sweeper pointed out, that is just the Runnable interface. I just don't like the naming, since I immediately associate it with multithreading.
For comparison:
#FunctionalInterface
public interface Runnable {
public abstract void run();
}

Related

What is the purpose of interface inside a Java class?

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.

Calling generic Java function with <?> parameter

Is the following possible somehow?
interface Foo<T> {
public void bar(T object);
}
...
public void callBar(Foo<?> foo) {
foo.bar("Hello world!");
}
Clearly, this is not type-safe as it is assuming that Foo<?> in this case actually is a Foo<String>.
But rather than the usual "unchecked" warning, this actually gives me the following error: The method bar(capture#1-of ?) in the type Foo is not applicable for the arguments (String)
Usually there's some casting I can do to turn this exception into the warning I want, but somehow I can't find one right now...
Any thoughts (other than "don't do this!", please)?
EDIT:
It seems like everyone does want to discuss the "don't do this", so let me explain the entire problem I'm trying to solve as elegantly as possible and then maybe someone has a cleaner way to do this...
I'm trying to write a flexible eventbus system, where I don't need to declare a billion interface types for each event.
I want to have a class EventBus that looks like this:
public class EventBus<GroupType, EventType> {
...
public void addHandler(EventHandler<GroupType, EventType, ?> handler, GroupType group, EventType... events) {
// ^ this is the <?> !!!
// add handler to list of handlers for group and requested event types
}
public <Source> void fireEvent(GroupType group, EventType event, Source source) {
// call all handlers registered for group and event type
}
}
where the interface EventHandler looks like this:
public interface EventHandler<GroupType, EventType, Source> {
public void onEvent(GroupType group, EventType event, Source source);
}
That way, I can simply write my event handlers to look like this:
public class Handler implements EventHandler<Groups, Events, TextBox> {
public void onEvent(Groups group, Events event, TextBox source) {
// Do something with source immediately
}
}
where Groups and Events are Enums that describe the possible event types.
Then I register them with
addHandler(myHandler, Groups.EDIT_BOXES, Events.VALUE_CHANGED, Events.CLEARED, ...);
And I can call them with
fireEvent(Groups.EDIT_BOXES, Events.VALUE_CHANGED, myEditField);
In my code, I know that in the group EDIT_BOXES all sources are of type TextBox and I don't want to type-cast my life away in every handler I write. That's why I would like to be able to implement the specific interface in the handler, but call it with an unsafe typecast from the EventBus (which I write once and hide forever) rather than having to write all my handlers like this:
public class Handler implements EventHandler<Groups, Events> {
public void onEvent(Groups group, Events event, Object source) {
TextBox usableSource = (TextBox) source;
// Do something with usableSource
}
}
And if the cast is wrong, the program will and should crash and burn either way. Even if I put an "instanceof" check in the handler, I will need to somehow throw that as an error. I can do that elegantly, but it doesn't really matter, since any error in this scenario is a bug in the code that needs to be fixed and not some runtime user-error, which I should gracefully inform the user of.
Now, I've seen other libraries implement a completely type-safe event system, but often this involves having to declare interfaces for every possible type of event and every possible type of event handler and sometimes even for functions on the eventbus itself, which, if you ask me, is WAY more pain than it's worth.
If any of you have a clean way to do what I'm trying to achieve, I'd be stoked. But I'm not sure it's doable any other way.
You propose that this is a solution:
public void callBar(Foo<?> foo) {
((Foo<String>) foo).bar("Hello world!");
}
I claim that if this does work that there is something wrong with your API's typing.
One possibility is that all the places where callBar is going to be called, the foo will actually be a Foo<String>. But if that is the case, then the (generic) method signature is incorrect. You should declare it as:
public void callBar(Foo<String> foo) {
foo.bar("Hello world!");
}
Another possibility is that the bar method will actually work just fine when called with an argument that doesn't match the generic type; e.g.
Foo<Integer> f = ...
f.bar("Hello world!");
doesn't cause any runtime breakages due to "Hello world!" having the wrong time. In that case you have probably declared the method signature in the interface incorrectly. It should be:
public void bar(Object object);
A third possibility is that your code works for a particular implementation of the Foo.bar method, and that you are only going to use it with those implementations. But if that is the case, your code should reflect this:
public void callBar(Foo<?> foo) {
if (foo instanceof SomeFooImpl) {
foo.realBar("Hello world!");
} else {
throw InvalidArgument("barring the wrong kind of foo");
}
}
and
public class SomeFooImpl<T> implements Foo<T> {
...
public void bar(T object) {
realBar(object);
}
publiC void realBar(Object object) {
System.out.print("Breaker breaker - come in '" + object + "'"));
}
}
(Note we can't overload bar and realBar; i.e. give them the same name. The methods need to have different erased signatures ...)
But the bottom line is that what you are proposing as the correct solution is liable to result in the foo method being called with an actual argument that doesn't match the base type. That is WRONG, at least from perspective of the type signatures as you have declared them.
UPDATE in response to your comment.
I think that the best solution is to change this:
public interface EventHandler<GroupType, EventType, Source> {
public void onEvent(GroupType group, EventType event, Source source);
}
to
public interface EventHandler<GroupType, EventType> {
public void onEvent(GroupType group, EventType event, Object source);
}
This means that a specific handler will need to type-cast the source object to the type that it is expecting. But this is pretty much mandated your EventBus API ... which seems to be saying that the handler registration and dispatching is agnostic of the source type of the handler objects. It is probably good from a functional perspective too, because it allows a single handler to handle events from multiple source types.
(Comment: your API design looks like you might be focussing too much on elegant use of generics ... at the expense of supporting the functionality that an event bus needs to provide. My conception of an event bus is that it should avoid static dependencies between the suppliers and consumers of events. This means that it needs to be able to dynamically "deal with" type mismatches between the the producers and consumers. But your use of generics seems to be (re-)introducing static type dependencies ... )
If you have a generic interface, don't make the method call it with a specific type. Or don't use a specific type and stay generic
interface Foo<T> {
public void bar(T object);
}
class SomeGenericClass {
public <T> void callGenericBar(Foo<T> foo, T param) {
foo.bar(param);
}
public void callStringBar(Foo<String> foo) {
foo.bar("Hello");
}
}
If you do it like
public void callBar(Foo<?> foo) {
((Foo<String>) foo).bar("Hello world!");
}
The following code will compile fine:
interface Foo<T> {
public void bar(T object);
}
class StringFoo implements Foo<String> {
public void bar(String object) {
System.out.println(object);
}
}
class IntFoo implements Foo<Integer> {
public void bar(Integer object) {
System.out.println(object);
}
}
class TestClass {
public static void callBar(Foo<?> foo) {
((Foo<String>) foo).bar("Hello world!");
}
public static void main(String[] args) {
StringFoo foo1 = new StringFoo();
IntFoo foo2 = new IntFoo();
callBar(foo1);
callBar(foo2);
}
}
But: once you run it you get
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
It requires that foo is a Foo<String>. Use
public static void callBar(Foo<String> foo) {
foo.bar("Hello world!");
}
And if you have multiple types of Foo use method overloading.
Never mind... Just figured it out:
public void callBar(Foo<?> foo) {
((Foo<String>) foo).bar("Hello world!");
}

Implementing Generic Interface in Java

I have a Java generics question I was hoping someone could answer. Consider the following code:
public interface Event{}
public class AddressChanged implements Event{}
public class AddressDiscarded implements Event{}
public interface Handles<T extends Event>{
public void handle(T event);
}
I want to implement this Handles interface like this:
public class AddressHandler implements Handles<AddressChanged>, Handles<AddressDiscarded>{
public void handle(AddressChanged e){}
public void handle(AddressDiscarded e){}
}
But java doesn't allow implementing Handles twice using the Generic. I was able to accomplish this with C#, but cannot figure a workaround in java without using Reflection or instanceof and casting.
Is there a way in java to implement the Handles interface using both generic interfaces? Or perhaps another way to write the Handles interface so the end result can be accomplished?
Going after #Amir Raminfar, you can use visitor pattern
interface Event{
void accept(Visitor v);
}
interface Visitor {
void visitAddressChanged(AddressChanged a);
void visitAddressDiscarded(AddressDiscarded a);
}
class AddressChanged implements Event{
#Override
public void accept(Visitor v) {
v.visitAddressChanged(this);
}
}
class AddressDiscarded implements Event{
#Override
public void accept(Visitor v) {
v.visitAddressDiscarded(this);
}
}
class AddressHandler implements Visitor {
void handle(Event e){
e.accept(this);
}
public void visitAddressChanged(AddressChanged e){}
public void visitAddressDiscarded(AddressDiscarded e){}
}
You can't do that in Java. You can only implement one concrete realization of the same generic interface. I would do this instead:
public class AddressHandler implements Handles<Event>{
public void handle(Event e){
if(e instanceof AddressDiscarded){
handleDiscarded(e);
} else if(e instanceof AddressChanged){
handleChanged(e);
}
}
public void handleDiscarded(AddressDiscarded e){}
public void handleChanged(AddressChanged e){}
}
No, because different "concrete" generic types in Java compile to the same type. The actual interface your object will implement is:
public interface Handles {
public void handle(Event event);
}
And, obviously, you can't have two different methods with an identical signature...
AFAIK you cannot do that, because when compiling the source code in Java these will both boil down to handle(Event), making the method ambiguous.
The generic information is not available during runtime in Java, in contrast to C#. That is why there it works as you describe.
You will have to change the method names to make them unique, like handleAddressChanged and handleAddressDiscarded.
This is indeed one of the weak points of Java generics.
Unfortunately not. The usual solution (fat, ugly, fast) is to create one Handles interface (i.e. HandlesAddressChange, HandlesAddressDiscarded) and give each of them a different method (handleAddressChange(...), handleAddressDiscarded()).
That way, the Java runtime can tell them apart.
Or you can use anonymous classes.
It isn't allowed because Java erases generic signatures during compilation. The interface method will actually have the signature
public void handle(Object event);
So you have two choices. Either implement separate Handlers for different events:
public class AddressChangedHandler implements Handles<AddressChanged>{ /* ... */ }
public class AddressDiscardedHandler implements Handles<AddressDiscarded>{ /* ... */ }
or implement one handler for all but check the type of the incoming event:
public void handle(Event e){
if (e instanceof AddressChanged) {
handleAdressChanged(e);
}
else if (e instanceof AddressDiscareded) {
handleAdressDiscarded(e);
}
}
An implementation like this won't work due to the constraints of the java specification.
But if you're not afraid to use AOP or some sort of an IOC-Container you could use annotations for that. Than your Aspects or the container could manage the messaging infrastructure and call the methods you annotate.
First you have to create the annotations.
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface EventConsumer {}
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface Handles{}
The you may annotate your class like that:
#EventConsumer
public class AddressHandler{
#Handles
public void handle(AddressChanged e){}
#Handles
public void handle(AddressDiscarded e){}
}
If you don't mind using a (small) library, here's one I wrote that solves your problem:
https://github.com/bertilmuth/requirementsascode
You'd build a model like this
Model.builder()
.on(AddressChanged.class).system(this::handleAddressChanged)
.on(AddressDiscarded.class).system(this::handleAddressDiscarded)
.build()
and run it.
How to do that exactly is described on the website.

Java Polymorphism - Selecting correct method based on subtype

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.

Java polymorphic methods

In Java i have abstract class named Operation and three its subclasses called OperationActivation, OperationPayment and OperationSendEmail.
ADDED FROM COMMENT: Operation* objects are EJB Entity Beans so I can't have business logic inside them.
No I want to create processor class like this:
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
process(operation);
}
public void process(OperationActivation operationActivation) {
out.println("process Activation");
}
public void process(OperationPayment operationPayment) {
out.println("process Payment");
}
public void process(OperationSendEmail operationSendEmail) {
out.println("process OperationSendEmail");
}
}
Processing each operation requires different logic so I want to have three different methods , one for each operation.
Of course this code doesn't compile. Am I missing something or it can't be done that way?
You are mixing up overloading and polymorphic method handling. When you overload methods based on the parameter type, that is static polymorphism. Those methods should be called from code that knows at compile-time what the type is. You could possibly do the following, but it wouldn't be clean object-oriented code:
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
if (operation instanceof OperationActivation)
process((OperationActivation)operation);
else if (operation instanceof OperationPayment)
process((OperationPayment)operation);
...
}
public void process(OperationActivation operationActivation) {
out.println("process Activation");
}
...
}
It would be much better to let the automatic run-time polymorphism work, by doing as Brian Agnew suggested, and making process be a method of each Operation subtype itself.
Shouldn't your Operation* objects be doing the work themselves ? So you can write (say)
for (Operation op : ops) {
op.process();
}
You can encapsulate the logic for each particular operation in its own class, and that way everything related to OperationPayment remains in the OperationPayment class. You don't need a Processor class (and so you don't need to modify a Processor class everytime you add an Operation)
There are more complex patterns to enable objects to mediate wrt. what they need to execute, but I'm not sure you need something that complex at this stage.
Assumption: Operation* objects are subclasses of Operation
Unless the processOperation(Operation) method is performing some common functionality, you could just remove it and expose the process(Operation) methods.
The Command Pattern (JavaWorld Explanation) might be useful, but it's tricky to tell exactly what properties you want from your question.
The problem with the code is that any object that matches one of the process(Operation*) methods will also match the process(Operation) method. As there are 2 methods that can be used, the compiler is warning you of an ambiguous situation.
If you really want/need the code above, I would suggest implementing the process(Operation*) methods, and modify the process(Operation) method so it is called processCommon(Operation). Then, the first thing each process(Operation*) does is call processCommon.
Alternatively, you can code exactly as Avi said, using instanceof comparisons.
Neither is ideal, but it will accomplish what you want.
So you have an abstract class called 'Operation' and it has 3 classes extending it. Not sure if this is what you are after but I'd imagine it be designed something like this:
Operation.java
public abstract class Operation {
public abstract void process();
}
OperationActivation.java
public class OperationActivation extends Operation {
public void process() {
//Implement OperationActivation specific logic here
}
}
OperationPayment.java
public class OperationPayment extends Operation {
public void process() {
//Implement OperationPayment specific logic here
}
}
OperationSendEmail.java
public class OperationSendEmail extends Operation {
public void process() {
//Implement OperationSendEmail spepcific logic here
}
}
ProcessOperationService.java
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
operation.process();
}
}
Won't the Visitor pattern be of use here ?
The class Operation can declare an "accept" method that takes a Visitor object and the subclasses can have provide the implementation :
public interface IOperationVisitor {
public void visit (OperationActivation visited);
public void visit (OperationPayment visited);
public void visit (OperationSendEmail visited);
}
abstract class Operation {
public void accept(IOperationVisitor visitor)();
}
class OperationActivation extends Operation {
public void accept(IOperationvisitor visitor) {
visitor.visit(this);
}
}
Similarly define "accept" method for classes OperationPayment and OperationSendEmail ..
Now your class can implement the visitor :
public class ProcessOperationService implements IOperationVisitor {
public void processOperation(Operation operation) {
operation.accept(this);
}
public void visit (OperationActivation visited) {
// Operation Activation specific implementation
}
public void visit (OperationPayment visited) {
// OperationPayment specific implementation
}
public void visit ((OperationSendEmail visited) {
// (Operation SendEmail specific implementation
}
}

Categories