简体   繁体   English

如何在Spring框架中实例化使用泛型的Object?

[英]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. 来自Spring XML配置。

Can that be done? 可以这样做吗? How? 怎么样?

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. 正如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 - 实际上,没有什么能阻止它创建一个Dao并在某些方法中传入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类型是要参数化的,也不能用它做任何事情。

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. 我的意思是Java泛型是语法糖,所以你创建一个bean的类型是无关紧要的。 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. 你可以将它注入任何一个Dao(或Dao)就好了,此时它将使用它注入的任何类型的隐式转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM