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);
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
If you need to instantiate an object of a class via a Class object and you need to use a constructor that has parameters, you can do so by calling getConstructor(Class []) on the Class object to get a Constructor object, and then you can call newInstance(Object []) on the Constructor object to instantiate the object.
Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.
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);
Using Spring ClassUtils and BeanUtils classes you can avoid dealing with those tedious exceptions that is Spring handling for you :
Constructor<Car> constructor = ClassUtils.getConstructorIfAvailable(Wheels.class, Etc.class);
Car car = BeanUtils.instantiateClass(constructor, new Wheels(), new Etc());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With