实例化Java中的通用对象

编程入门 行业动态 更新时间:2024-10-23 22:26:59
本文介绍了实例化Java中的通用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以像下面的代码片段中那样在Java中实例化通用对象?我知道在C#中是可能的.但是,我还没有在Java中看到类似的机制.

Is it possible to instantiate generic objects in Java as does in the following code fragment? I know that it is possible in C#. But, I haven not seen a similar mechanism yet in Java.

// Let T be a generic type. T t = new T();

推荐答案

不,由于类型擦除,在Java中不起作用.在执行代码时,代码不知道T是什么.

No, that doesn't work in Java, due to type erasure. By the time that code is executing, the code doesn't know what T is.

请参阅 Java泛型FAQ 有关Java泛型的更多信息: )-特别是,请参见类型擦除部分.

See the Java Generics FAQ more more information about Java generics than you ever wanted :) - in particular, see the Type Erasure section.

如果出于这种原因或其他原因需要在执行时知道T的类型,可以将其存储在Class<T>中,并将其放入构造函数中:

If you need to know the type of T at execution time, for this or other reasons, you can store it in a Class<T> and take it in the constructor:

private Class<T> realTypeOfT; public Foo(Class<T> clazz) { realTypeOfT = clazz; }

然后您可以呼叫newInstance()等.

更多推荐

实例化Java中的通用对象

本文发布于:2023-08-04 17:37:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   对象   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!