Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a general DynamoDBMarshalling for enums

I'm using Amazon Web Services SDK for Java for DynamoDB; trying to suffice the interface for @DynamoDBMarshalling:

Class<? extends DynamoDBMarshaller<? extends Object>> marshallerClass();

I build a marshaller that receives any Enum:

public class EnumMarshaller<T extends Enum<T>> implements DynamoDBMarshaller<T>
{
    @Override
    public String marshall(T getterReturnResult)
    {
        return getterReturnResult.toString();
    }

    @Override
    public T unmarshall(Class<T> clazz, String obj)
    {
        return Enum.valueOf(clazz, obj);
    }
}

The problem is that when I'm trying to use the annotation on my field I can't figure it out:

public static enum MyEnum {BLA, BLA2}

@DynamoDBMarshalling(marshallerClass=EnumMarshaller<MyEnum>.class)
    public MyEnum getStatus()
    {
        return status;
    }

I can't call .class on a generic type and some other tries came up different errors. I'm starting to think it's impossible with Amazon's contract...

like image 788
Chen Harel Avatar asked Apr 08 '12 15:04

Chen Harel


2 Answers

The following worked fine to me:

The Marshaller:

public class EnumMarshaller implements DynamoDBMarshaller<Enum> {
    @Override
    public String marshall(Enum getterReturnResult) {
        return getterReturnResult.name();
    }

    @Override
    public Enum unmarshall(Class<Enum> clazz, String obj) {
        return Enum.valueOf(clazz, obj);
    }
}

In my table class with an enum:

@DynamoDBMarshalling(marshallerClass=EnumMarshaller.class)
@DynamoDBAttribute(attributeName = "MyEnum")
public MyEnum getMyEnum() {
   return myEnum;
}
like image 102
Tiago Peres França Avatar answered Sep 23 '22 02:09

Tiago Peres França


I worked around this problem by sub-classing the JsonMarshaller with a specific class type:

public class FooMarshaller extends JsonMarshaller<Foo>
{
    // No impl required
}

Then the marshalling annotation is added to the data property like:

@DynamoDBMarshalling(marshallerClass = FooMarshaller.class)
public Set<Foo> getFoos()
{
    return foos;
}

A pain if you have to add many class types, but it works.

like image 26
Joe Avatar answered Sep 26 '22 02:09

Joe