Creating new instance from Class with constructor parameter
java, reflection
Solution
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);
Problem
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? Edit: 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); ```