Java StringToIntegerConverter

This post shows you how to convert String to Integer in Java. Let's write a generic code in this post.

Create Generic Converter interface

/**
 * Converts objects of S type to T type.
 */
public interface Converter<S, T> {

    /**
     * Converts the source object from S type to T type.
     *
     * @param source the object to convert
     *
     * @return the converted object
     */
    T convert(S source);

}

Converts String to Integer - StringToIntegerConverter.java

Let's implement above Converter interface to convert String to Integer in Java
/**
 * Converts String to Integer.
 */
public class StringToIntegerConverter implements Converter<String, Integer> {

    @Override
    public Integer convert(String source) {
        return Integer.valueOf(source);
    }

}

Comments