Sending parameters using newInstance()?

F

frank

Was wondering when using something like this
theClass= (myClass)Class.forName(className).newInstance();

it calls the classes (className in this case) default constructor with
no arguments right? How do you send values/arguments to it? Or can't
that be done?

Thanks,

Frank
 
P

Patricia Shanahan

frank said:
Was wondering when using something like this
theClass= (myClass)Class.forName(className).newInstance();

it calls the classes (className in this case) default constructor with
no arguments right? How do you send values/arguments to it? Or can't
that be done?

Thanks,

Frank

The Class newInstance method is a simple way of doing simple cases.

Use the getConstructor method in the Class object to obtain the
Constructor for your parameter types. Constructor has a newInstance
method that takes a parameter array.

Patricia
 
F

frank

Thanks would you happen to have an example?

Patricia said:
The Class newInstance method is a simple way of doing simple cases.

Use the getConstructor method in the Class object to obtain the
Constructor for your parameter types. Constructor has a newInstance
method that takes a parameter array.

Patricia
 
A

Adam Maass

frank said:
Thanks would you happen to have an example?

Assume you have a class like this:

class A {
A (int i, float f) { ... }
}


then you can write code like this:

Constructor c = A.class.getConstructor(new Class[]{Integer.TYPE,
Float.TYPE});
A a = (A)c.newInstance(new Object[]{new Integer(1), new Float(1.0f)});
 
A

A_Wieminer

Was wondering when using something like this
Assume you have a class like this:
class A {
A (int i, float f) { ... }
}

Constructor c = A.class.getConstructor(new Class[]{Integer.TYPE,
Float.TYPE});
A a = (A)c.newInstance(new Object[]{new Integer(1), new Float(1.0f)});

For this reason if can lock your code to a homemade/stable interface you
can survive with the simple way. I often make the following design,
where I add init(...) method to make actual initialization. I then
simple use classForName and call init method with appropriate params.

theClass=(MyClass)Class.forName(className).newInstance();
theClass.init(123, 12.123);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top