我希望能够逐个字段指定Converter的类型。为此,我创建了一个注释,以指定要使用的所需转换器类。我还创建了一个实现GenericConverter和ConditionalConverter的类。我从getConvertibleTypes
返回null表示我要检查所有源对。在matches
方法内部,我将检查是否存在我的自定义注释,然后使用指定的转换器类。我的问题是,当我调用save
时,仅以matches
作为sourceType和Long
作为targetType来调用ObjectId
方法。我是用正确的方法吗?
public class ConvertWithConditionalConverter implements GenericConverter, ConditionalConverter {
@Override
public boolean matches(TypeDescriptor sourceTypeDesc, TypeDescriptor targetTypeDesc) {
// Only ever gets called with Long and ObjectId
System.out.println("Source: " + sourceTypeDesc.getName() + ", Target: " + targetTypeDesc.getName());
return false;
}
@Override
public @Nullable Set<ConvertiblePair> getConvertibleTypes() {
// Returning null indicates all source-to-target pairs should be considered.
return null;
}
@Override
public Object convert(@Nullable Object source, TypeDescriptor sourceTypeDesc, TypeDescriptor targetTypeDesc) {
// Never gets called
System.out.println("Source: " + sourceTypeDesc.getName() + ", Target: " + targetTypeDesc.getName());
return null;
}
}
我要使用字段注释的注释
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ConvertWith {
Class<? extends Converter> value();
}