Metadataを活用し、動的にDtoを作る
JavascriptからDataを取得する場合、Entityの一部のみで良い場合が良くあります。
その度に、Dtoを作るのが面倒ですので、slim3のMetadataを使用して、作るRoutineを書いてみました。
使用方法は、
private LginMeta m = LginMeta.get(); DtoAdhoc da = DatastoreUtil.dto().add(m.logi, m.name, m.sec); HashMap hm = da.toMapWithKeyJSON(res); //尚一回だけの使用であれば下記の様に勿論書けます。流れるインターフェースは良いですね。 HashMap hm = DatastoreUtil.dto().add(m.logi, m.name, m.sec).toMapWithKeyJSON(res);
ソースは下記の様に簡単です。
public class DatastoreUtil { public static DtoAdhoc dto() { return new DtoAdhoc(); } } public class DtoAdhoc { private ArrayListfields = new ArrayList(); private BeanDesc beanDesc; public DtoAdhoc add(CoreAttributeMeta... flds) { for (CoreAttributeMeta fld : flds) { fields.add(fld.getName()); } return this; } public HashMap toMap(Object o) { HashMap res = new HashMap(); for (String fld : fields) { res.put(fld, getBeanDesc(o).getPropertyDesc(fld).getValue(o)); } return res; } public HashMap toMapWithKeyJSON(Object o) { HashMap res = toMap(o); res.put("key", JSON.encode(getBeanDesc(o).getPropertyDesc("key") .getValue(o))); return res; } protected BeanDesc getBeanDesc(Object o) { if (beanDesc != null) { return beanDesc; } beanDesc = BeanUtil.getBeanDesc(o.getClass()); return beanDesc; } }