views:

511

answers:

3

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 List performTheService(String word, Class 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

+3  A: 

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.

Bozho
Hi BozhoI am just learning here. Can I instantiatenew GenericService<String>() or new GenericService<Long>() using spring context.My generic class contains public <T extends WordplayService> List<S> performTheService(String word, Class<T> clazz) { try { 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
Shreeni
You can safely use DI with generics, because as I said, generics are lost at the time when the dependencies are injected.
Bozho
Thanks, That clarifies.I did see that I can access generic type info at runtime using reflection. But it seems way too complex and is definitely not designed to inject beans with concrete types
Shreeni
+1  A: 

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.

Stephen C
A: 

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

sparkle