In development, we often need to convert between different types. In order to improve the readability and security of the code, Java's generic mechanism provides powerful type checking capabilities. This article shares the design and implementation of a general converter that implements type safety through generics.
Converter interface
First, we define a generic interfaceTransformer<T, R>
, used to describe the type fromT
To typeR
The conversion behavior:
public interface Transformer<T, R> { R transform(T input); }
Singleton converter implementation
byLong
arriveDate
For example, we implement a singleton converter:
import ; public class LongToDateTransformer implements Transformer<Long, Date> { private static final LongToDateTransformer INSTANCE = new LongToDateTransformer(); private LongToDateTransformer() {} public static LongToDateTransformer getInstance() { return INSTANCE; } @Override public Date transform(Long input) { return new Date(input); } }
By setting the constructor to private and providing agetInstance
Method to ensure the uniqueness of the converter.
General storage and acquisition
To facilitate management of various converters, we can use oneMap
Store the converter by type:
import ; import ; public class TransformerRegistry { private final Map<String, Transformer<?, ?>> registry = new HashMap<>(); public <T, R> void register(Class<T> sourceType, Class<R> targetType, Transformer<T, R> transformer) { String key = () + "->" + (); (key, transformer); } @SuppressWarnings("unchecked") public <T, R> Transformer<T, R> get(Class<T> sourceType, Class<R> targetType) { String key = () + "->" + (); return (Transformer<T, R>) (key); } }
Example of usage
Examples of registering and using converters are as follows:
TransformerRegistry registry = new TransformerRegistry(); (, , ()); Transformer<Long, Date> transformer = (, ); Date date = (1698507600000L); (date);
Summarize
Generic and singleton modes enable a type-safe, easy to scale universal converter system. In complex projects, this design can effectively reduce type conversion errors and improve code robustness and maintenance.
This is the end of this article about Java generic type converter implementing type safety. For more related Java generic type conversion content, please search for my previous article or continue browsing the related articles below. I hope you will support me in the future!