Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/560867/how-do-i-instantiate-an-object-that-uses-generics-with-spring-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...