如何使用 Class<T>在爪哇? [英] How to use Class&lt;T&gt; in Java?

查看:22
本文介绍了如何使用 Class<T>在爪哇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题上对泛型以及它们在幕后真正做了什么进行了很好的讨论,所以我们都知道Vector是一个整数数组的向量,而HashTable是一个键为字符串和值的表.然而,让我难受的是 Class<> 的用法.

There's a good discussion of Generics and what they really do behind the scenes over at this question, so we all know that Vector<int[]> is a vector of integer arrays, and HashTable<String, Person> is a table of whose keys are strings and values Persons. However, what stumps me is the usage of Class<>.

java 类 Class 也应该采用模板名称,(或者我被 eclipse 中的黄色下划线告知).我不明白我应该在那里放什么.Class 对象的全部意义在于当您没有完全了解对象的信息时,用于反射等.为什么它让我指定 Class 对象将保存哪个类?我显然不知道,或者我不会使用 Class 对象,我会使用特定的对象.

The java class Class is supposed to also take a template name, (or so I'm being told by the yellow underline in eclipse). I don't understand what I should put in there. The whole point of the Class object is when you don't fully have the information about an object, for reflection and such. Why does it make me specify which class the Class object will hold? I clearly don't know, or I wouldn't be using the Class object, I would use the specific one.

推荐答案

使用 Class 类的泛型版本,您可以编写诸如

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

然后你可以确定你收到的 Class 对象扩展了 Collection,并且这个类的一个实例(至少)是一个 Collection.

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

这篇关于如何使用 Class<T>在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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