Java Generic: Type Inference
By admin on May 10, 2008 in Java, Programming
This is a simple trick I just recently found out.
I have a Generic interface
1: public interface Generic<T> {
2:
3: }
And the implementation
1: public class GenericImpl<T> implements Generic<T> {
2:
3: public static <V> Generic<V> make() {
4: return new GenericImpl<V>();
5: }
6:
7: }
Normally I do this
1:
2: public class GenericTest {
3:
4: public static void main(String[] args){
5: Generic<String> obj = new GenericImpl<String>();
6: }
7: }
To avoid the redundancy of specifying the type every time, I defined the generic make method in the GenericImpl class. So now the code becomes
1:
2: public class GenericTest {
3:
4: public static void main(String[] args){
5: Generic<String> newObj = GenericImpl.make();
6: }
7: }
The type is derived implicitly.
Post a Comment