使用T参数通用的方法肯定是很方便的.但是,我很好奇如果你将一个参数传递给方法,泛型方法的用途是什么Class<T> clazz.我想出了一个可能有用的案例.也许您只想根据类的类型运行方法的一部分.例如:
/** load(File, Collection<T>, Class<T>)
* Creates an object T from an xml. It also prints the contents of the collection if T is a House object.
* @return T
* Throws Exception
*/
private static <T> T void load(File xml, Collection<T> t, Class<T> clazz) throws Exception{
T type = (T) Jaxb.unmarshalFile(xml.getAbsolutePath(), clazz); // This method accepts a class argument. Is there an alternative to passing the class here without "clazz"? How can I put "T" in replace of "clazz" here?
if (clazz == House.class) {
System.out.println(t.toString());
} else {
t.clear();
}
return T;
}
Run Code Online (Sandbox Code Playgroud)
这是一种公认的做法吗?Class<T> clazz参数何时对泛型方法有用?
chr*_*her 11
这是一种公认的做法吗?
好吧,对我来说......不是没有.对我来说,当你可以简单地在类型上定义一些边界时似乎毫无意义T.例如:
private static <T extends House> void load(Collection<T> t)
Run Code Online (Sandbox Code Playgroud)
这将保证对象是类型House或子类的House,但如果你只想要一个类型的实例House或它的子类,那么它应该只是:
private static void load(Collection<House> houses)
Run Code Online (Sandbox Code Playgroud)
泛型的想法是使方法或类更具有可塑性和可扩展性,因此对于我来说,开始比较方法体中的类类型似乎是违反直觉的,当泛型的概念是从这些细节中抽象出来时.
| 归档时间: |
|
| 查看次数: |
5957 次 |
| 最近记录: |