Creating new instance from Class with constructor parameter
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);
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());
You have to get to the relevant Constructor
object (e.g. via Class.getConstructors
or Class.getConstructor
) and then call constructor.newInstance
, giving it the arguments it requires.
An example you can use is as follows: lets say conn is a connection to the database.
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 allows you to pass in arguments to the constructor.
class Compresor<T> {
private Class<? extends T> clazz;
Compresor(final Class<? extends T> cls){
this.clazz = cls
}
}
精彩评论