Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation of generic type using Spring Config

How can I instantiate a bean with generic type using Spring config

public class GenericService<T> 
{
 ...
}

Note that T is not the concrete type of a bean property. It is really just the type for one of the methods of the service.

In other words.. Can I instantiate new GenericService of type String or new GenericService of type Long using Spring context.

My generic class contains

public <T extends WordplayService> List<S> performTheService(String word, Class<T> clazz) 
{ 
    return clazz.newInstance().getAllWords(); 
    ...
}

The return type of the generic method depends on the concrete parameter type of the class instantiated. Is this possible or a wrong usage of DI + generics? TIA

like image 973
Shreeni Avatar asked Nov 30 '09 08:11

Shreeni


3 Answers

Generics are a compile-time concept, while spring context is loaded at runtime, so they don't intersect. What exactly are you trying to achieve? What is your usecase.

like image 189
Bozho Avatar answered Sep 24 '22 01:09

Bozho


You can safely use DI with generics, because as I said, generics are lost at the time when the dependencies are injected.

Generics are a compile-time concept ...

The truth is, Generic information is not (completely) erased at compile time. You can still retrieve this information via reflection, and that is what the Spring DI container does already for collections. See 3.3.3.4.2. Strongly-typed collection (Java 5+ only) in 2.0.8 Spring documentation (sorry can only post one hyperlink).

However, I do not know (yet) if it is possible to instruct the container to do that for your custom classes as well.

If you want to know how to retrieve this information at runtime, here's the original post from Neal Gafter: http://gafter.blogspot.com/2006/12/super-type-tokens.html

like image 26
sparkle Avatar answered Sep 24 '22 01:09

sparkle


You should just instantiate it using the raw class name. As @Bozho says generics are a compile-time only construct and their full types are not available at runtime.

like image 33
Stephen C Avatar answered Sep 26 '22 01:09

Stephen C