java - 在 pojo 中存储未知对象的列表
问题描述
我想要的是
我想将带有对象列表的 pojo 作为 json 对象存储到集合中。我不知道什么对象被插入到我的 pojo 中,这就是为什么我需要让它尽可能通用。我的方法
我使用来自 mongo db 的反应流框架。应该包含对象列表的 Pojo
public class Entity {
public ObjectId id;
public String type;
public int version;
public Set<Object> components;
public Entity() { }
public Entity(ObjectId id, String type, int version, Set<Object> components) {
this.id = id;
this.type = type;
this.version = version;
this.components = components;
}
}
我作为某种测试对象创建的 pojo。
public class Chunk {
public ObjectId id;
public int x;
public int y;
public Set<ObjectId> inChunk;
public Chunk() { }
public Chunk(int x, int y, Set<ObjectId> entities) {
this.x = x;
this.y = y;
this.inChunk= entities;
}
}
我的主要
public static void main(String[] args) throws Throwable {
var pojoCodecRegistry = fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().register(Object.class).automatic(true).build())
);
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connString)
.codecRegistry(pojoCodecRegistry)
.retryWrites(true)
.build();
// Receiving database and collection
var mongoClient = MongoClients.create(settings);
var database = mongoClient.getDatabase("Test");
var collection = database.getCollection("Entity", Entity.class);
// Create an entity to fill it with components and insert it
var entity = new Entity(new ObjectId(), "player", 1, new LinkedHashSet<>());
var chunk = new Chunk(1,2, new LinkedHashSet<>());
entity.components.add(chunk);
// Insert it
var operationSubscriber = new SubscriberHelpers.OperationSubscriber<>();
collection.insertOne(entity).subscribe(operationSubscriber);
operationSubscriber.await();
// Receive it
var printDocument = new SubscriberHelpers.PrintSubscriber<>("YO : ");
collection.find().subscribe(printDocument);
printDocument.await();
mongoClient.close();
}
问题
保存的对象正在被插入,但它缺少它的对象 ID。此外,加载后,entity.components 会被一个对象填充。但是这个对象只是来自 java 的原始“Object.class”,我不能将那个对象转换为我保存的“Chunk.class”。所以它在加载时不知何故忘记了它的类型,我无法访问它。我的问题
如何在我的 Entity.class 中保存“未知”对象的列表,并确保它使用以前的类型正确加载?此外,我想知道子文档是否也可以引用其他“Entity.class”。就像在 Entity.components 中有一个“Chunk.class”,它引用了一些其他“Entity.class”对象(注意,不是子文档)。如果是这样的话,他们会自动加载吗?还是我需要自己实现?
我很高兴有任何帮助,谢谢!
解决方案
推荐阅读
- android - 使用 JUnit 5 进行 ViewModel UI 测试
- python - 从黄砖 KElbowVisualizer 中提取 k
- javascript - 使用带有asp.net mvc的cropper js没有在文本框中获取选定的照片名称
- unity3d - Unity web gl游戏不会显示加载屏幕,只是黑屏
- python - 如何遍历n维列表并找到所有组合
- c# - 如果我不在 WinForms 上使用 Thread.Sleep,BackgroundWorker 将不起作用
- ffmpeg - 将 MOV 转换为 WEBM,带 alpha 通道,不损失质量
- javascript - 如何在 iOS Safari 中触发横向全屏?
- python - 尝试将元素从文本文件导入列表
- python - Pandas 在 case when 语句后无法选择 NaN 行