Home
>
Java > Using static Factory-methods to create Generics
Using static Factory-methods to create Generics
Today I browsed through
Project Coin and had a closer look at the
language changes that made it into Java 7. Especially the proposal named
‘Improved Type Inference for Generic Instance Creation’ attracted my attention, because I already discovered a technique in Joshua Bloch’s great book
Effective Java (2nd Edition) that helped me to reduce the effort to create Generics.
All you need is a Factory-class with static methods:
| 1 | |
| 2 | package com.java_blog.generics; |
| 3 | import java.util.HashMap; |
| 4 | |
| 5 | public class GenericsFactory { |
| 6 | public static <K, V> HashMap<K, V> newHashMap() { |
| 7 | return new HashMap<K, V>(); |
| 8 | } |
| 9 | } |
If you import these methods statically into your code, Generics-creation becomes very handy:
| 01 | package com.java_blog.generics; |
| 02 | |
| 03 | import java.util.HashMap; |
| 04 | import static com.java_blog.generics.GenericsFactory.newHashMap; |
| 05 | |
| 06 | public class GenericsTest { |
| 07 | public static void main(String[] args) { |
| 08 | |
| 09 | // old style |
| 10 | HashMap<String, Integer> oldMap = new HashMap<String, Integer>(); |
| 11 | |
| 12 | // new style |
| 13 | HashMap<String, Integer> newMap = newHashMap(); |
| 14 | } |
| 15 | } |
Happy Coding,
Tino
tino Java Generics, Java
But you can also apply this technique on self-created-Generics that are not available in Google Collections like e.g. MyGeneric<T1,T2,T3>.
Tino.