使用 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;
}
这是公认的做法吗? Class<T> clazz
什么时候参数对泛型方法有用吗?
最佳答案
Is this an accepted practice?
嗯,对我来说.. 不,不是真的。对我来说,当您可以简单地在 T
的类型上定义一些边界时,这似乎有点毫无意义。例如:
private static <T extends House> void load(Collection<T> t)
这将保证对象是 House
类型或 House
的子类,但是如果您只想要一个House
类型的实例或其子类,它实际上应该是:
private static void load(Collection<House> houses)
泛型的思想是使方法或类更具延展性和可扩展性,所以对我来说,开始比较方法体中的类类型似乎违反直觉,而泛型的真正概念是从此类中抽象出来详情。
关于java - 什么时候可以将 Class<T> 参数传递给泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380872/