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

我的情况是我的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(); // .. } } 

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

编辑:

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

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

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

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

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

使用Spring ClassUtils和BeanUtils类可以避免处理Spring为您处理的繁琐exception:

 Constructor constructor = ClassUtils.getConstructorIfAvailable(Wheels.class, Etc.class); Car car = BeanUtils.instantiateClass(constructor, new Wheels(), new Etc()); 

您必须访问相关的Constructor对象(例如,通过Class.getConstructorsClass.getConstructor ),然后调用constructor.newInstance ,为其提供所需的参数。

您可以使用的示例如下:假设conn是与数据库的连接。

 Class[] btarray = { conn.getClass() }; try{ if (classname != null) { pmap = (Mapper) Class.forName( classname).getConstructor(btarray).newInstance( new Object[] { conn }); } } catch (Throwable x) { x.printStackTrace(Log.out); } 

btarray允许您将参数传递给构造函数。

 class Compresor { private Class clazz; Compresor(final Class cls){ this.clazz = cls } }