如何在Java通用方法中初始化实例

埃拉德·本达(Elad Benda)2

我有以下代码:

    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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章