Generic data type conversion method

前端 未结 5 853
走了就别回头了
走了就别回头了 2020-12-25 14:31

This question is in response to another question by opensas: building a generic initializer function in java

From his question it became clear that he needs to conve

5条回答
  •  -上瘾入骨i
    2020-12-25 15:05

    Take a look at Variance, which allows you to set up a type conversion context with various converters registered and then move values into and out of a Variant type with type conversion handled by the context.

    Variant aVariant = Variant.of("1.2345");
    double aDouble = aVariant.doubleValue();
    
    int anInt = Variant.of("12").intValue();
    String aString = Variant.of(12.0).toString();
    Date aDate = Variant.of("2012-04-06").as(Date.class);
    String anIsoFormattedDate = Variant.of(aDate).in(isoDateFormattingContext).toString()
    

    Converters are just Guava Functions from one type to another, and you can register your own, overriding existing conversions where desired.

提交回复
热议问题