Java 如何实例化使用 Spring 框架的泛型的对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/560867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I instantiate an Object that uses generics with Spring framework?
提问by flybywire
I have a class that looks like this:
我有一个看起来像这样的课程:
class Dao<T>{
...
}
I want to do this:
我想做这个:
new Dao<Student>();
from the Spring XML configuration.
来自 Spring XML 配置。
Can that be done? How?
可以做到吗?如何?
采纳答案by matt b
Reading up about type erasureshould 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.
在运行时,泛型类的类型参数被擦除。意思是,正如 cletus 所说,Java 中的泛型基本上是语法糖——它们只是一个编译时特性。
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.
由于 Spring 在运行时实例化对象,它实际上可以自由地实例化Dao
任何类型的 a - 实际上,没有什么可以阻止它创建 aDao
并Student
在某些方法中传递类型并Teacher
在另一个中传递类型。
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.
所以基本上答案是,Spring 不知道该Dao
类型是要参数化的,并且不能用它做任何事情。
回答by cletus
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.
你做不到,你做不到的原因是它实际上毫无意义。我的意思是 Java 泛型是语法糖,所以创建 bean 的类型无关紧要。您可以将它注入到任何带有 Dao(或 Dao)的东西中,此时它将使用它被注入的任何类型的隐式转换。