由于类型擦除,您无法实例化通用对象。通常,您可以保留对
Class表示该类型的对象的引用,并使用它来调用
newInstance()。但是,这仅适用于默认构造函数。由于要使用带参数的构造函数,因此需要查找
Constructor对象并将其用于实例化:
protected <T> T getProperty(String key, T fallback, Class<T> clazz) { String value = properties.getProperty(key); if (value == null) { return fallback; } else { //try getting Constructor Constructor<T> constructor; try { constructor = clazz.getConstructor(new Class<?>[] { String.class }); } catch (NoSuchMethodException nsme) { //handle constructor not being found } //try instantiating and returning try { return constructor.newInstance(value); } catch (InstantiationException ie) { //handle InstantiationException } catch (IllegalAccessException iae) { //handle IllegalAccessException } catch (InvocationTargetException ite) { //handle InvocationTargetException } }}但是,看到实现此目标有多大麻烦,包括使用反射的性能成本,值得首先研究其他方法。
如果您绝对需要采用这种方法,并且
T仅限于编译时已知的一组不同类型,则可以选择保留s 的静态
Map值
Constructor,该静态值在启动时加载-
这样,您就不必动态在每次调用此方法时查找它们。例如,使用静态块填充的
Map<String,Constructor<?>>or 。
Map<Class<?>,Constructor<?>>



