Spring Type Converter Example

Spring GenericConversionService provides method to convert one data type to another data type, here is one to convert String to Integer and String to List.

Example

package com.pretech;
import java.io.IOException;
import java.util.List;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.GenericConversionService;
public class SpringTypeConverterExample {
	public static void main(String[] args) throws IOException {
		
		GenericConversionService springconversionService = ConversionServiceFactory.createDefaultConversionService();
		//Integer to String
		
		String str = springconversionService.convert(222,String.class);
		System.out.println(str);
		
		//String to Integer
		
		Integer integer = springconversionService.convert("100",Integer.class);
		System.out.println(integer);
		
		//Comma separated String to List
		List<String> list = springconversionService.convert("sunday,monday,tuesday",List.class);
		for(String st: list){
			System.out.println("List values :"+st);
		}
		
	}
}

Output



222
100
List values :sunday
List values :monday
List values :tuesday


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts