com.datastax.driver.extras.codecs.enums.EnumNameCodec Maven / Gradle / Ivy
Show all versions of driver-cql-shaded Show documentation
/*
* Copyright DataStax, Inc.
*
* This software can be used solely with DataStax Enterprise. Please consult the license at
* http://www.datastax.com/terms/datastax-dse-driver-license-terms
*/
package com.datastax.driver.extras.codecs.enums;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.extras.codecs.ParsingCodec;
/**
* A codec that serializes {@link Enum} instances as CQL {@code varchar}s representing their
* programmatic names as returned by {@link Enum#name()}.
*
* Note that this codec relies on the enum constant names; it is therefore vital that
* enum names never change.
*
* @param The Enum class this codec serializes from and deserializes to.
*/
public class EnumNameCodec> extends ParsingCodec {
private final Class enumClass;
public EnumNameCodec(Class enumClass) {
this(TypeCodec.varchar(), enumClass);
}
public EnumNameCodec(TypeCodec innerCodec, Class enumClass) {
super(innerCodec, enumClass);
this.enumClass = enumClass;
}
@Override
protected String toString(E value) {
return value == null ? null : value.name();
}
@Override
protected E fromString(String value) {
return value == null ? null : Enum.valueOf(enumClass, value);
}
}