16

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);
5
  • Why do you need to tell Compressor what kind of objects to create? What kinds of classes will be used here? Commented Dec 8, 2010 at 11:29
  • 1
    Have you considered using an abstract factory for this rather than hacking it with reflections? Commented Dec 8, 2010 at 13:19
  • I guess the question is complete now. Any additional information is perhaps for another question. Commented Dec 8, 2010 at 15:16
  • It would be great if somebody could write a proper answer based on all the information above so I could accept it. Commented Dec 8, 2010 at 17:38
  • @Ihahne - the additional information does not seem directly related to this question. And there is no question there at all. Commented Dec 9, 2010 at 12:10

5 Answers 5

18

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean Compressor.class.getConstructor(Class.class).newInstance(someparameter);
@lhahne well, since your parameter is of type Class, it can be Some.class
Simple example: CreateObjects is a java class, Can invoke newInstance by the below way without any arguments for constructor. CreateObjects obj2 = CreateObjects.class.getConstructor().newInstance();
4

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());

Comments

1

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.

Comments

0

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.

Comments

-1
class Compresor<T> {
    private Class<? extends T> clazz;
    Compresor(final Class<? extends T> cls){
        this.clazz = cls
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.