Skip to content

Instantly share code, notes, and snippets.

@Swedz
Last active May 25, 2020 08:54
Show Gist options
  • Save Swedz/7b752f226cab9fece746adb7056c82e5 to your computer and use it in GitHub Desktop.
Save Swedz/7b752f226cab9fece746adb7056c82e5 to your computer and use it in GitHub Desktop.
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
public abstract class AbstractEnum<T> {
private final Class<T> clazz;
protected List<T> elements;
/**
* Automatically registers the {@link T}s.
*/
public AbstractEnum(Class<T> clazz) {
this.clazz = clazz;
this.elements = Lists.newArrayList();
this.registerAll();
}
/**
* Register all of the {@link T}s using reflection.
*/
protected void registerAll() {
try {
// Register every non-deprecated field
for(Field field : this.getClass().getFields()) {
// Make sure the field is "public static final"
if(Modifier.isPublic(field.getModifiers()) &&
Modifier.isStatic(field.getModifiers()) &&
Modifier.isFinal(field.getModifiers()) &&
this.clazz.isAssignableFrom(field.getType())) {
// Get our generic value
T value = (T) field.get(null);
// Make sure our field has a valid value
if(value == null)
throw new IllegalArgumentException("Field " + field.getName() + " is null!");
// Make sure the field is not deprecated
if(field.isAnnotationPresent(Deprecated.class))
continue;
// Register our field
this.elements.add(value);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Get all of the elements in the enum.
*
* @return the {@link List} for the {@link T}s
*/
public List<T> values() {
return this.elements;
}
/**
* Get the iterator for the enum.
*
* @return the {@link Iterator} for the {@link T}s
*/
public Iterator<T> iterator() {
return this.elements.iterator();
}
}
public class AbstractEnumExample extends AbstractEnum<SomeClass> {
/*
* These do not need to be the same class as SomeClass, they can be superclasses.
*/
public static final SomeClass VALUE1 = new SomeClass();
public static final SomeClass VALUE2 = new SomeClass();
public static final SomeClass VALUE3 = new SomeClass();
/*
* Make sure this part is defined at the bottom of the class or else it will not be able to read all of your values you included above. To access this you could just use AbstractEnumExample.getInstance() and then use values() or iterator() to get the values from above.
*/
private static final AbstractEnumExample INSTANCE = new AbstractEnumExample();
private AbstractEnumExample() {
super(SomeClass.class);
}
public static AbstractEnumExample getInstance() {
return INSTANCE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment