views:

1244

answers:

3

I have a class that looks like this:

class Dao<T>{
...
}

I want to do this

new Dao<Student>();

from the Spring XML configuration.

Can that be done? How?

A: 

See this forum post. You can basically use Dao as your bean's class, however I don't know if this is satisfactory for you.

kgiannakakis
+1  A: 

You can't do it and the reason you can't do it is that it actually means nothing. By that I mean that Java generics are syntactic sugar so what type you create a bean with is irrelevant. You can inject it into anything taking a Dao (or Dao) just fine at which point it'll be using the implicit casting of whatever type it's been injected into.

cletus
+6  A: 

Reading up about type erasure should help you understand this a bit better.

At runtime, the type parameters for a generic class are erased. Meaning, as cletus said, generics in Java are basically syntactic sugar - they are only a compile-time feature.

Since Spring is instantiate objects at run-time, it is actually free to instantiate a Dao of any type - and actually, there is nothing stopping it from creating a Dao and passing in Student types in some methods and Teacher types in another.

So basically the answer is, Spring has no idea that the Dao type is meant to be parameterized and can't do anything with it.

matt b