我有以下代码:
public <V> V getPropertiesByObject(V sample) throws TimeoutException {
//settings fields using reflaction
return sample;
}
我这样称呼它:
MyClass a = getPropertiesByObject(new MyClass());
仅仅是因为我不知道如何构造一个实例。
我会选择:
public <V> V getPropertiesByObject(Class<V> sample) throws TimeoutException {
//how to create a new V instance?
return result;
}
有没有办法重构我的原始代码?
如果V
具有无参数的构造函数,则可以使用Class<V>::newInstance()
。
public <V> V getPropertiesByObject(Class<V> sample) throws TimeoutException {
V result = sample.newInstance();
// stuff on V
return result;
}
当然,您将像这样使用它: MyClass a = getPropertiesByObject(MyClass.class)
如果必须指定一些参数,则可以执行以下操作:
public <V> V getPropertiesByObject(Class<V> sample, Object... params) throws TimeoutException {
V result = sample.newInstance();
result.param0 = params[0];
result.param1 = params[1];
// etc
return result;
}
但是在两种情况下,都MyClass
必须具有无参数的构造函数。如果您无法编辑MyClass
,则应使用的波西米亚答案Constructor
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句