Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I instantiate an Object that uses generics with Spring framework?

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?

like image 619
flybywire Avatar asked Feb 18 '09 12:02

flybywire


People also ask

Can you instantiate a generic?

Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type, that has a type parameter E .

How do you declare a generic Object in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.


1 Answers

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.

like image 169
matt b Avatar answered Oct 05 '22 19:10

matt b