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
参数对泛型方法有用?