0

I've got set of classes: TestClass1, TestClass2 and TestClass3. All those classes inherits from class MainTestClass. Classes TestClass1, TestClass2 and TestClass3 has different constructors. For example:

TestClass1(String s)
TestClass2(Integer i)
TestClass3(Double d)

Classes can have more than one constructor - each different from others.

Now I want to randomly create instances of these classes and store them in List. To do that, I store Class objects of TestClass1, ... using TestClass1.class, ... in a List. Then, I get for example first constructor of each class, that has non-zero parameters count. Now, when I want to create object using newInstance() method, I don't know types and count of arguments to pass to this specific constructor.

Is it possible to achieve something like this using reflection? I have been thinking about something like

setConstructorArgument(int number, Object value)

or

setConstructorArguments(Object[] arguments)

Do similar methods exists in Java?

2
  • 3
    the Constructor object has a newInstance method that takes arguments. You can also interrgate the constructor to get the argument types and quantity. Commented Mar 25, 2013 at 0:28
  • Okay, my fault. I didn't know, you can substitute Object... initargs with Object[] initargs. You can post your comment as answer and I'll accept it as correct one. Thanks :) Commented Mar 25, 2013 at 0:51

1 Answer 1

3

A Constructor Object has a newInstance method that can take arguments to construct the class it belongs to. Obviously the arguments have to match the parameters expected the getParameterTypes method can provide those.

Object... initargs does in fact mean Object[] initargs, except it allows the syntax

newInstance(param1, param2, param3);

as well as

newInstance(new Object[]{param1, param2, param3});

You should also bear in mind that

newInstance(null);

does not mean

newInstance(new Object[]{null});

which catches out people from time to time.

personally I do not like varargs, but c'est la vie.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.