使用构造函数参数从Class创建新实例

lha*_*hne 16 java reflection

我的情况是我的Java类需要创建大量特定类型的对象.我想给出作为参数创建的对象类的名称.另外,我需要在构造函数中为创建的类赋一个参数.我有类似的东西

class Compressor {

    Class ccos;

    public Compressor(Class ccos) {
        this.ccos = ccos;
    }

    public int getCompressedSize(byte[] array) {
        OutputStream os = new ByteArrayOutputStream();
        // the following doesn't work because ccos would need os as its constructor's parameter
        OutputStream cos = (OutputStream) ccos.newInstance();
        // ..
    }
}
Run Code Online (Sandbox Code Playgroud)

你有什么想法我可以解决这个问题吗?

编辑:

这是一个研究项目的一部分,我们需要评估具有多个不同输入的多个不同压缩机的性能.Class ccosOutputStream从Java的标准库,Apache Compress Commons或lzma-java 压缩而来的.

目前我有以下似乎工作正常.其他想法是受欢迎的.

OutputStream os = new ByteArrayOutputStream();
OutputStream compressedOut = (OutputStream) ccos.getConstructor(OutputStream.class).newInstance(os);
final InputStream sourceIn = new ByteArrayInputStream(array);
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 17

您可以使用该Class.getConstructor(paramsTypes...)方法并调用newInstance(..)构造函数.在你的情况下:

Compressor.class.getConstructor(Class.class).newInstance(Some.class);
Run Code Online (Sandbox Code Playgroud)