Consider this interface:
public interface Listenable {
void listen();
}
Consider this implementation:
public class Listener implements Listenable {
public void listen() {
System.out.println("I am listening");
}
}
Now I am doing remoting via RMI and I am passing instances of such classes to server (maybe some black-magic proxies are spawn there, not sure).
The only solution I was able to invent so far, and I have to say it’s pretty idiotic, is to add this code to Listener class:
public class Listener implements Listenable {
private double id;
private Random rand = new Random();
public Listener() {
this.id = rand.nextDouble();
}
public void listen() {
System.out.println("I am listening");
}
public int hashCode() { ... } // calculate from id
// same for equals - compare by id
}
This usually works, but we all know how evil this is :/ How should one deal with such a situation?
UPDATE:
Stanard equals did not work for me, because instances are over different VMs (I mentioned remoting), so it couldn’t work. I will need some state variable after all, or suggest something good for comparing such classes on remote VMs. I am very sorry for confusion.
Make the listener an enum singleton:
Then there will be only one instance of
Listenerand equality is guaranteed.You may not want to expose the fact that you’re using an
enumfor this or even that the listener is a singleton at all. What you can do is make the enum a private inner enum of some class with static methods (calledListenables, let’s say) and just expose this implementation through a static method: