Analysis of Spring's ConversionService

1: Description

This is the interface used by spring for data type conversion definition. The function is simple to use with JDK's PropertyEditor
. The source code is as follows:

org . springframework . core . convert . ConversionService
 public  interface  ConversionService  { 
	// Whether the sourceType type can be converted to the targetType type 
	boolean  canConvert ( @Nullable Class < ? > sourceType , Class < ? > targetType ) ; 
	// type descriptor of sourceType, whether or not A type descriptor that can be converted to targetType 
	boolean  canConvert ( @Nullable TypeDescriptor sourceType , TypeDescriptor targetType ) ;
	// Convert source to targetType 
	@Nullable 
	< T > T convert ( @Nullable Object source , Class < T > targetType ) ; 
	// Convert source+sourceType to targetType 
	@Nullable 
	Object convert ( @Nullable Object source ,  @Nullable TypeDescriptor sourceType , TypeDescriptor targetType ) ; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

1: Test

@Test 
public  void  testConversionService ( )  {
    DefaultConversionService cs
            =  new  DefaultConversionService ( ) ; 
    // Check if int can be converted to String (true) 
    boolean intToStringCanConvert = cs . canConvert ( int . class , String . class ) ; 
    System . out . println ( "intToStringCanConvert: " ) ; 
    System . out . println ( intToStringCanConvert ) ; 
    // Check if map type can be converted to int type 
    boolean mapToIntCanConvert= cs . canConvert ( Map . class ,  int . class ) ; 
    System . out . println ( "mapToIntCanConvert: " ) ; 
    System . out . println ( mapToIntCanConvert ) ; 
    String intInStringType =  "900" ; 
    // result of converting String to int 
    Integer targetIntType = cs . convert ( intInStringType ,  int .class ) ; 
    System . out . println ( "targetIntType: " ) ; 
    System . out . println ( targetIntType ) ; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

run:

intToStringCanConvert:
true
mapToIntCanConvert:
false
targetIntType:
900

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Tags: Analysis of Spring's ConversionService

spring java spring

Related: Analysis of Spring's ConversionService