【发布时间】: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