Symbol in Java

One of the nice features of JavaScript is called the Symbol. In a nutshell it is similar to a constant, but it’s value is different from every instance that gets created.

A common refactoring pattern that would use something like this would be the Null Object pattern. With the pattern, you can simply do

public static final URI SYM_A = new URI ("/x");
public static final URI SYM_B = new URI ("/y");

This is all well and good if you had a constructor that would give you to construct an object. Though you still need to make sure the actual data itself is not equal other wise `.equals` will return `true`. So you’d need to remember to check for equality with `==` rather than `.equals`

Another issue is if you had a large interface but no concrete implementations available like `io.vertx.core.buffer.Buffer` then you’d have a lot of boiler plate work to go through each method.

The contract

What we need is an API that would pass the following assertions given the code.

MyClass a = newSymbol(MyClass.class);
MyClass b = newSymbol(MyClass.class);

assert a == a;
assert b == b;

assert a.equals(a);
assert b.equals(b);

assert a != b;
assert ! a.equals(b);