T
- the case classV
- the value that the class holds (e.g. String)public abstract class CaseClasses<T,V> extends Object
Manages objects that are like enums in that they are constant, but unlike enums in that new instances can be created during runtime. This class ensures that all instances of a class are unique, so they can be safely compared using "==" (provided their constructors are private).
This class awkwardly mimics the "case class" feature in Scala.
Example:
public class Color { public static final CaseClasses<Color, String> VALUES = new ColorCaseClasses(); public static final Color RED = new Color("red"); public static final Color GREEN = new Color("green"); public static final Color BLUE = new Color("blue"); private final String name; // Constructor should be PRIVATE in order to prevent users from // instantiating their own objects and circumventing the CaseClasses // object. private Color(String name) { this.name = name; } public String getName() { return name; } // CaseClasses implementation is an inner class because the Color // constructor is private. private static class ColorCaseClasses extends CaseClasses<Color, String> { public ColorCaseClasses() { super(Color.class); } @Override protected Color create(String value) { return new Color(value); } @Override protected boolean matches(Color object, String value) { return object.getName().equalsIgnoreCase(value); } } } public class Test { @Test public void test() { assertTrue(Color.RED == Color.VALUES.find("Red")); assertTrue(Color.RED == Color.VALUES.get("Red")); assertNull(Color.VALUES.find("purple")); Color purple = Color.VALUES.get("purple"); assertEquals("purple", purple.getName()); assertTrue(purple == Color.VALUES.get("Purple")); } }
Constructor and Description |
---|
CaseClasses(Class<T> clazz)
Creates a new case class collection.
|
Modifier and Type | Method and Description |
---|---|
Collection<T> |
all()
Gets all the static constants of the case class (does not include
runtime-defined constants).
|
protected abstract T |
create(V value)
Creates a new instance of the case class.
|
T |
find(V value)
Searches for a case object by value, only looking at the case class'
static constants (does not search runtime-defined constants).
|
T |
get(V value)
Searches for a case object by value, creating a new object if one cannot
be found.
|
protected abstract boolean |
matches(T object,
V value)
Determines if a case object is "equal to" the given value.
|
public CaseClasses(Class<T> clazz)
clazz
- the case classprotected abstract T create(V value)
value
- the value to give the instanceprotected abstract boolean matches(T object, V value)
object
- the case objectvalue
- the valuepublic T find(V value)
value
- the valuepublic T get(V value)
value
- the valuepublic Collection<T> all()
Copyright © 2012–2023 Michael Angstadt. All rights reserved.