我想用JOOq创建一个通用方法,该方法使用来自JSON对象的值更新表(由字符串指定)。我在这个例子中没有包括任何表/字段的验证。
public void updateTable(String table, JsonObject data) {
Table<?> table = PUBLIC.getTable(table);
UpdateSetFirstStep<?> update = DSL.using(fooConfig).update(table);
// Loop through JSON {field1: value1, field2: value2, ...}
for (Map.Entry<String, Object> entry : data) {
String fieldName = entry.getKey();
Field<?> field = table.field(fieldName);
Object value = entry.getValue();
// error: no suitable method found for set(Field<CAP#1>,CAP#2)
update.set(field, field.getType().cast(value));
}
}
但是我收到编译时错误:no suitable method found for set(Field<CAP#1>,CAP#2)
。
我认为问题在于编译器不知道字段的类型和值的类型是相同的(因此CAP#1和CAP#2)。
有没有办法实现这个目标?
答案 0 :(得分:2)
我认为问题在于编译器不知道字段的类型和值的类型是相同的(因此CAP#1和CAP#2)。
这是确切的问题。相同通配符类型的两种不同用法会产生两种不同的新捕获类型。
解决方案是引入一个小方法,其中通配符类型使用一次并绑定到类型参数。当它绑定到类型参数时,编译器会识别它的不同用法是指相同的类型。
像这样:
public void updateTable(String name, JsonObject data) {
Table<?> table = PUBLIC.getTable(name);
UpdateSetFirstStep<?> update = DSL.using(fooConfig).update(table);
// Loop through JSON {field1: value1, field2: value2, ...}
for (Map.Entry<String, Object> entry : data) {
String fieldName = entry.getKey();
Field<?> field = table.field(fieldName);
Object value = entry.getValue();
// Here the wildcard type is bound to the
// type variable of the updateField method
updateField(update, field, value);
}
}
public <T> void updateField(UpdateSetStep<?> update, Field<T> field, Object value) {
// When the wildcard is bound to T it can be used
// multiple times without a problem
update.set(field, field.getType().cast(value));
}
...是将字段类型转换为某种具体类型:
@SuppressWarnings("unchecked")
Field<Object> field = (Field<Object>) table.field(fieldName);
update.set(field, field.getType().cast(entry.getValue()));
这样可以输入更少的代码,在这个简单的示例中它可以正常工作。但它的类型安全性也较低,因此在更复杂的代码中引入带有类型参数的方法可能更好。
例如,以下类型检查但可能在运行时崩溃:
update.set(field, entry);
...将能够为Field
:
<T> Field<T> field = table.field(fieldName);
但当然这不是合法的Java,类型变量只能作为类和方法的参数引入,而不能作为局部变量引入。
...是定义一个util方法并将一个lambda对象传递给它。它的工作方式与第一个解决方案相同,但您不必为要执行此操作的每件事创建自定义方法。
// Loop through JSON {field1: value1, field2: value2, ...}
for (Map.Entry<String, Object> entry : data) {
String fieldName = entry.getKey();
Field<?> field = table.field(fieldName);
Object value = entry.getValue();
captureType(field, f -> update.set(f, f.getType().cast(value)));
}
public static <T> void captureType(T o, Consumer<T> c) {
c.accept(o);
}
这种方法的一个变体是使用一些现有的方法得到相同的结果:
Optional.of(field).ifPresent(f -> update.set(f, f.getType().cast(value)));
答案 1 :(得分:1)
最简单的解决方案是使用UpdateSetStep.set(Map<? extends Field<?>, ?>)
方法。它适用于相当宽松的类型安全,为您进行数据类型转换(如果可能):
public void updateTable(String table, JsonObject data) {
Table<?> table = PUBLIC.getTable(table);
DSL.using(fooConfig)
.update(table)
.set(data.entrySet()
.stream()
.map(e -> new SimpleImmutableEntry(table.field(e.getKey()), e.getValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue)))
.where(...) // Don't forget this! ;-)
.execute();
}