使用构造函数参数从Class创建新实例 [英] Creating new instance from Class with constructor parameter

查看:160
本文介绍了使用构造函数参数从Class创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have situation where my Java class needs to create a ton of certain kind of objects. I would like to give the name of the class of the objects that are created as a parameter. In addition, I need to give the created class a parameter in its constructor. I have something like

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();
        // ..
    }
}

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

Do you have any ideas how I could remedy this?

编辑:

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

This is part of a research project where we need to evaluate the performance of multiple different compressors with multiple different inputs. Class ccos is a compressed OutputStream either from Java's standard library, Apache Compress Commons or lzma-java.

目前我有以下似乎工作正常。欢迎其他想法。

Currently I have the following which appears to work fine. Other ideas are welcome.

OutputStream os = new ByteArrayOutputStream();
OutputStream compressedOut = (OutputStream) ccos.getConstructor(OutputStream.class).newInstance(os);
final InputStream sourceIn = new ByteArrayInputStream(array);


推荐答案

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

You can use the Class.getConstructor(paramsTypes...) method and call newInstance(..) on the constructor. In your case:

Compressor.class.getConstructor(Class.class).newInstance(Some.class);

这篇关于使用构造函数参数从Class创建新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆