我正在尝试将Java / Scala对象转换为Protocol Buffers消息。
我的对象名为IDSNumber
,它有doubleValue
方法,返回java.lang.Double
。我试图让它在Dozer对象转换期间自动转换为double。
我在Scala中创建了一个Dozer Custom Converter,这里:
class IDSConverter extends DozerConverter[IDSNumber, java.lang.Double](classOf[IDSNumber], classOf[java.lang.Double]) {
def convertTo(source: IDSNumber, destination: java.lang.Double): java.lang.Double = {
source.doubleValue()
}
def convertFrom(source: java.lang.Double , destination: IDSNumber): IDSNumber = {
new IDSNumber(source)
}
}
My Protocol Buffers消息如下所示(shortFee
和longFee
应该从IDSNumber
类型转换):
message PerformanceSettingMessage {
optional string displayCurrency = 1;
optional PeriodMessage performancePeriod = 2;
optional int64 conversionDate = 3;
optional BenchmarkOptionsMessage benchmarkOptions = 4;
optional string investmentStrategyMeaning = 5;
optional double shortFee = 6;
optional double longFee = 7;
}
我尝试以下列方式使用转换器:
val longFee = new IDSNumber(2.0)
val shortFee = new IDSNumber(3.0)
// newing up a real performance settings object with IDSNumbers for shortFee and longFee
val performanceSettings = new PerformanceSettings(Currency.apply("$"), period, fj.data.Option.none(), fj.data.Option.none(), Investment_Weighted, shortFee, longFee)
val mapper = new DozerBeanMapper() // new DozerMapper
val idsConverter = new IDSConverter() // my IDSNumber converter
mapper.setCustomConverters(java.util.Arrays.asList(idsConverter)) // make it use my IDSNumber converter
val msg = mapper.map(performanceSettings, classOf[PerformanceSettingMessage]) // map my real performanceSettings object to my PerformanceSettingsMessage generated by Protocol Buffers
当我运行上述代码时,msg
将shortFee
和longFee
都设置为0.0
,而不是2.0
和3.0
。对我做错了什么的想法?也许有更好的方法(更好的库?)来回转换这些对象?谢谢!