如何使用Class< T>在Java? [英] How to use Class<T> in Java?

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

问题描述

有关泛型及其在幕后的真正做法的一个很好的讨论,在这个问题,所以我们都知道 Vector 是整数数组的向量, HashTable< String,Person> 是其键的字符串和值 Person 的表。
然而,什么困扰我的是 Class<> 的用法。



code> Class 也应该采取模板名称(或者我被eclipse中的黄色下划线告诉我)。我不明白我应该放在那里。 Class 对象的整个点是当你不完全有关于对象的信息,反射等。为什么它让我指定 Class 对象将保存的类?我显然不知道,或者我不会使用 Class 对象,我会使用具体的一个。

使用类的类的泛化版本允许你写入

等东西。

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

然后你可以确定你收到的Class对象扩展 Collection ,这个类的实例将是(至少)一个集合。


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<>.

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.

解决方案

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

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

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&lt; T&gt;在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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