All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.evrythng.commons.EnumUtils Maven / Gradle / Ivy

/*
 * (c) Copyright 2012 EVRYTHNG Ltd London / Zurich
 * www.evrythng.com
 */
package com.evrythng.commons;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 * Utility class for the enums.
 */
public class EnumUtils {

	/**
	 * Creates an enum value from a string using a lookup map (usually created by {@link #createNames(Object[])}.
	 * 

* Typical implementation: *

*

	 * public static MyEnum fromString(String name) {
	 * 	return EnumUtils.fromString(names, name);
	 * }
	 * 
* * @return The enum value corresponding to the name. If the name is {@code null}, returns {@code null}. * * @throws IllegalArgumentException if the name is not {@code null} and does not match any enum value. */ public static E fromString(final Map names, final String name) { if (name == null) { return null; } E t = names.get(name); if (t == null) { throw new IllegalArgumentException("Invalid enum value."); } return t; } /** * Creates a lookup map for the enum names, intended for use with the {@link #fromString(Map, String)} method. It uses the * {@link #toString()} method to build the lookup map. This is intended to be used in a static initializer. *

*

	 * private static Map<String, MyEnum> names;
	 * static {
	 * 	names = EnumUtils.createNames(values());
	 * }
	 * 
* * @param values The enum values, as provided by {@code values()}. */ public static Map createNames(final E[] values) { Map names = new HashMap(); for (E t : values) { names.put(t.toString(), t); } return names; } /** * Returns an {@link EnumSet} representing the values of the array. * @param values The values. This can be {@code null} or empty. * @param The enum type. * @return The {@link EnumSet}. */ public static > EnumSet setOf(final E[] values) { if (values != null && values.length > 0) { return EnumSet.of(values[0], values); } else { return EnumSet.noneOf((Class) values.getClass().getComponentType()); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy