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

aQute.lib.json.EnumHandler Maven / Gradle / Ivy

The newest version!
package aQute.lib.json;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class EnumHandler extends Handler {
	@SuppressWarnings("rawtypes")
	final Class type;
	final Map	mapping	= new HashMap<>();

	public EnumHandler(Class type) {
		this.type = type;
		for ( Object constant : type.getEnumConstants()) {
			String s = JSONCodec.keyword(constant.toString().toLowerCase());
			mapping.put(s, constant);
		}
	}

	@Override
	public void encode(Encoder app, Object object, Map visited) throws IOException, Exception {
		StringHandler.string(app, JSONCodec.keyword(object.toString()));
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object decode(Decoder dec, String s) throws Exception {
		try {
			return Enum.valueOf(type, s);
		} catch (IllegalArgumentException e) {
			Object result = mapping.get(s);
			if (result != null) {
				throw new IllegalArgumentException(
					"enum constant " + s + " not found for " + type.getSimpleName() + " " + mapping.values());
			}
			return result;
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy