【问题标题】:Include sub-classes with generated Google Cloud Endpoint client library在生成的 Google Cloud Endpoint 客户端库中包含子类
【发布时间】:2016-03-13 20:36:16
【问题描述】:

我目前正在开发一个 Android 项目,该项目使用 Google Datastore 存储数据,并且可以通过带有 Objectify 库的 Cloud Endpoints 进行访问。 objectify 库在使用“@Subclass”注释解释多态性方面做得很好,但是我遇到的问题是,当我生成用于 Android 代码的客户端库时,子类不包括在内。有没有办法强制编译器包含这些类?

这是我正在做的一个基本示例。让我们以 Objectify 文档中的多态为例:

@Entity
public class Animal {
    @Id Long id;
    String name;
}

@Subclass(index=true)
public class Mammal extends Animal {
    boolean longHair;
}

@Subclass(index=true)
public class Cat extends Mammal {
    boolean hypoallergenic;
}

值得一提的是,这三个类都已使用“ObjectifyService.factory().register()”注册。使用上面的类,我的 api 中有一个类似于以下的方法:

@ApiMethod(
            name = "getAnimals", path = "zoo/getAnimals", httpMethod = ApiMethod.HttpMethod.GET
)
public Collection<Animal> getAnimals(final User user, @Named("IdList") Collection<Long> idList)
        throws UnauthorizedException {
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    Map<Long,Animal> animalMap = ofy().load().type(Animal.class).ids(idList);

    ArrayList<Animal> animals= new ArrayList<>();
    for (Long animalId:idList) {
        animals.add(animalMap.get(animalId));
    }
    return animals;
}

如您所见,最终的 ArrayList“动物”可能包含动物、哺乳动物或猫,但是生成的库只允许我访问 Animal 类。我需要确保子类可用于 Android 代码。编译器如何知道要包含哪些类,有没有办法强制添加一个类?多态性甚至会延续到客户端还是仅支持服务器端?

【问题讨论】:

    标签: java android google-app-engine objectify


    【解决方案1】:

    这不是一个很好的答案,但您可以公开一个返回这些类型的无操作 API(实际上只返回 null;)。这应该强制生成类。如果有更正式的方法可以做到这一点,请随时纠正我。

    【讨论】:

    • 我确实考虑过创建虚拟调用来强制添加类,但是这只是一种糟糕的做法,并决定反对它。我确实将原始调用更改为仅返回 Cat 对象,只是为了测试这是否会同时添加哺乳动物和动物类。我发现编译器生成的类根本不包含多态性。生成的 Cat 类扩展了 GenericJson 类,这让我觉得这个集合不会返回我希望的混合对象。我已经切换到 UI,但是当我测试原始调用时,我会分享我的结果。
    • 我采用的方法如下:在前端有一个接口来表示您的数据,例如 Animal,以及一个具体的 impl AnimalImpl,您可以从后端端点 json 类生成它。您的 Animal 可以形成接口和相应 impl 的层次结构。我也很喜欢这个,因为 json 垃圾是可变的,而你可以让你的前端实现不可变并保存任何额外的行为和数据。总的来说,对于前端架构恕我直言,json 的东西还不够健壮。祝你好运,很想看看你发现了什么!
    猜你喜欢
    • 2016-05-23
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多