如何从已上传的数据库表向source块中注入对应类型的agent?
可行实现方案(AnyLogic 环境)
首先完成前置配置:
- 提前在你 Source 块关联的 Agent 类型中新增参数,命名为
orderTypeId,类型可根据实际 OrderType 格式选择int/double,用来存储类型区分标识。 - 把代码中的
YourAgentType替换为你实际的 Agent 类名,source替换为你对应 Source 块的名称。
实现代码
// 遍历已构建的订单二维数组 for (int i = 0; i < ArrayCustomerOrders.length; i++) { // 取出当前行的订单类型和对应注入数量,若你本身存储的就是整数可省略强转逻辑 int currentOrderType = (int) ArrayCustomerOrders[i][0]; int orderCount = (int) ArrayCustomerOrders[i][1]; // 按数量批量注入同类型 Agent 并赋值标识 List<Agent> batchOrders = source.inject(orderCount); for (Agent order : batchOrders) { ((YourAgentType) order).orderTypeId = currentOrderType; } }
如果你需要对单个 Agent 做更复杂的初始化逻辑,也可以改成单条循环注入的写法:
for (int i = 0; i < ArrayCustomerOrders.length; i++) { int currentOrderType = (int) ArrayCustomerOrders[i][0]; int orderCount = (int) ArrayCustomerOrders[i][1]; for (int j = 0; j < orderCount; j++) { YourAgentType newOrder = (YourAgentType) source.inject(); newOrder.orderTypeId = currentOrderType; // 这里可以补充其他自定义初始化逻辑 } }
注意事项
- 调用
inject()时提示参数不匹配的问题,本质是不要用需要传入 Agent 构造参数的重载方法,直接调用无参/仅传入数量的重载方法,拿到返回的 Agent 实例后再手动赋值参数是兼容性最高的写法。 - 你当前用
double类型存储订单类型、订单数量,强转整数时要注意避免精度丢失,后续建议把这两个字段的存储类型调整为整数类型,减少潜在问题。
内容的提问来源于stack exchange,提问作者Rudolph
相关产品推荐
相关产品推荐

