Implementing Generic Interface in Java - 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.

Related

How to use double interfaces in multiple implementing classes in Java?

So lets assume I am having the following stuff defined:
public interface IExportTool {
void export(IReport iReport);
}
And then attempting to use it:
public class KibanaExporter implements IExportTool{
public void export(IReport kibana) {
kibana = (Kibana) kibana;
((Kibana) kibana).toJSON();
}
}
But there are also other classes which would again be doing something like that too:
public class MetricExporter implements IExportTool{
public void export(IReport metric) {
metric = (Metric) metric;
((Metric) metric).toJSON(); // might be something else here like toXML etc
}
}
Please note that both Kibana and Metric are implementing IReport<KibanaRow> and IReport<MetricRow> respectively, while the IReport interface looks like:
public interface IReport<T> {
void addRow(T row);
}
I don't like all this casting, this doesn't feel right nor gives me autocomplete, so any suggestion how to do it properly?
From what you've posted, it's clear that both Kibana and Metric are subtypes of IReport.
In that case, you can make the interface generic:
interface IExportTool<R extends IReport> {
void export(R iReport);
}
And then change the implementations in this fashion:
public class KibanaExporter implements IExportTool<Kibana>{
public void export(Kibana kibana) {
kibana.toJSON();
}
}
And:
public class MetricExporter implements IExportTool<Metric> {
public void export(Metric metric) {
metric.toJSON();
}
}
This version allows the compiler to understand and validate that only instances of subtypes of IReport will ever be passed to export(). Code using this will be validated by the compiler, such that MetricExporter().export() can only be called with an object of type Metric and KibanaExporter().export() with an object of type Kibana.
And with that, type casts are no longer needed.

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.

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
}
}

Design of inheritance for Validate interfaces

I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method validate that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say Validatable. The following are the two basic solutions I can have.
interface Validatable {
public void validate() throws ValidateException;
}
interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate() throws ValidateException {
throw new UnsupportedOperationException();
}
}
class Object2 implements Validatable {
...
public void validate() throws ValidateException {
...
}
}
This is the first solution whereby I have a general global interface that something that's validatable implements and I could use validate() to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes.
Alternatively I could have the following which would leave me without a top level interface.
interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate(Object1Converse converse) throws ValidateException {
...
}
}
interface Object2Validatable {
public void validate() throws ValidateException;
}
class Object2 implements Object2Validatable {
...
public void validate() throws ValidateException {
...
}
}
I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.
what about this :
interface Validatable {
void validate(Validator v);
}
class Object1 implements Validatable{
void validate(Validator v){
v.foo
v.bar
}
}
class Object1Converse implements Validator{
//....
}
class Object2 implements Validatable{
void validate(Validator v){
//do whatever you need and ingore validator ?
}
}
What do you care if Object2 receives an unneeded argument ? if it is able to operatee correctly without it it can just ignore it right ?
If you are worried about introducing an unneeded dependency between object2 and Object1Converse then simply specify an interface to decouple them and use that as the validator.
Now I must add that having a mixed model where you have both object able to self validate and object which need external state information to validate sounds weird.
care to illustrate ?
Perhaps the apache commons validator project would be useful here - either directly or as a model for how to attack your problem. They effectively have a parallel set of objects that do the validation - so there is no interface on the objects, just the presence/absence of a related validator for the object/class.
This is in C#, but the same ideas can certainly be implemented in many other languages.
public class MyClass {
//Properties and methods here
}
public class MyClassValidator : IValidator<MyClass> {
IList<IValidatorError> IValidator.Validate(MyClass obj) {
//Perform some checks here
}
}
//...
public void RegisterValidators() {
Validators.Add<MyClassValidator>();
}
//...
public void PerformSomeLogic() {
var myobj = new MyClass { };
//Set some properties, call some methods, etc.
var v = Validators.Get<MyClass>();
if(v.GetErrors(myobj).Count() > 0)
throw new Exception();
SaveToDatabase(myobj);
}
As simple solution to the "can an object be validated" problem is to add a third interface.
This third interface is an empty one that parents both of the others, meaning you can just check against that interface (Assuming you aren't worried about someone spoofing being validate-able), and then iteratively check against the possible validation interfaces if you need to actually validate.
Example:
interface Validateable
{
}
interface EmptyValidateable inherits Validateable //Or is it implements?
{
void validate() throws ValidateException;
}
interface Objectvalidateable inherits Validateable
{
void validate(Object validateObj);
}

Categories