denley / courier

A delivery service for Android Wear. Courier uses the DataApi and MessageApi to deliver objects between devices simply and cleanly.
Apache License 2.0
80 stars 5 forks source link

Class annotation to serialize an object to a DataMap #9

Closed denley closed 9 years ago

denley commented 9 years ago
@DataMap
public class User {

    public String username;
    public String emailAddress;

}
denley commented 9 years ago

This should create a binder class that looks like this:

import me.denley.courier.Packager.DataPackager;
import com.google.android.gms.wearable.DataMap;

public class User$$DataMapPackager<T extends User> implements DataPackager<T> {

    public DataMap pack(T target) {
        final DataMap map = new DataMap();
        pack(target, map);
        return map;
    }

    protected void pack(T target, DataMap map) {
        map.putString("username", target.username);
        map.putString("emailAddress", target.emailAddress);
    }

    public T unpack(DataMap map) {
        final User target = new User();
        unpack(map, target);
        return target;
    }

    protected void unpack(DataMap map, T target) {
        target.username = map.getString("username");
        target.emailAddress = map.getString("emailAddress");
    }

}
denley commented 9 years ago

This can then be inherited, like so:

@DataMap
public class ChildUser extends User {

    public int age;

}
public class ChildUser$$DataMapPackager<T extends ChildUser> extends User$$DataMapPackager<T> {

    protected void pack(T target, DataMap map) {
        super.pack(target, map);
        map.putInt("age", target.age);
    }

    public T unpack(DataMap map) {
        final T target = (T) new ChildUser();
        bind(map, target);
        return target;
    }

    protected void unpack(DataMap map, T target) {
        super.unpack(map, target);
        target.age = map.getInt("age");
    }

}