String classname to object?

M

mistral

Hello,

Is there a way to create an object instance if I only now the (string) name
of it's class?

Tom
 
C

Chris Smith

mistral said:
Is there a way to create an object instance if I only now the (string) name
of it's class?

If it has a constructor that doesn't need arguments, then you can simply
do:

Class.forName("com.mypack.MyClass").newInstance();

If you wish to use a constructor that does require arguments, then
you'll have to call getConstructor on the Class instance, and then call
Constructor's newInstance method.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
M

mistral

Chris said:
If it has a constructor that doesn't need arguments, then you can simply
do:

Class.forName("com.mypack.MyClass").newInstance();

If you wish to use a constructor that does require arguments, then
you'll have to call getConstructor on the Class instance, and then call
Constructor's newInstance method.

Tahnk you , problem solved !
 

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
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top