Created
February 23, 2013 20:07
-
-
Save jarek-przygodzki/5021128 to your computer and use it in GitHub Desktop.
Increased compile-time safety with phantom types http://www.javacodegeeks.com/2013/02/increased-compile-time-safety-with-phantom-types.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.javacodegeeks.com/2013/02/increased-compile-time-safety-with-phantom-types.html | |
public interface Entity { | |
Long getId(); | |
} | |
public final class Ref<T extends Entity> implements Serializable { | |
public final long id; | |
public static <T extends Entity> Ref<T> of(T value) { | |
return new Ref<T>(value.getId()); | |
} | |
public static <T extends Entity> Ref<T> of(long id, Class<T> clazz) { | |
return new Ref<T>(id); | |
} | |
@Override | |
public String toString() { | |
return String.valueOf(id); | |
} | |
private Ref(long id) { | |
this.id = id; | |
} | |
public long getId() { | |
return this.id; | |
} | |
@Override | |
public int hashCode() { | |
return (int) (id ^ (id >>> 32)); | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) | |
return true; | |
if (o == null || o.getClass() != this.getClass()) | |
return false; | |
Ref<?> other = (Ref<?>) o; | |
return other.id == this.id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment