如何实例化一个在Spring框架中使用泛型的对象? [英] How do I instantiate an Object that uses generics with Spring framework?

查看:269
本文介绍了如何实例化一个在Spring框架中使用泛型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Dao< T> {
...
}

我想这样做:

 新Dao< Student>(); 

来自Spring XML配置。



可以这样做吗?如何?

解决方案

阅读 type erasure 应该有助于你理解这一点。



在运行时,类型通用类的参数被擦除。意义,正如cletus所说,Java中的泛型基本上是句法糖 - 它们只是编译时的特征。

由于Spring在运行时实例化对象,实际上它可以自由地实例化任何类型的 Dao 实际上,在创建 Dao 并在某些方法中传入 Student 类型和<$ c

所以基本上答案是,Spring不知道 Dao type意味着被参数化,并且不能对它做任何事情。


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?

解决方案

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.

这篇关于如何实例化一个在Spring框架中使用泛型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆