Activator.CreateInstance in Java???

1,036 views
Skip to first unread message

nobita

unread,
Mar 5, 2008, 4:04:44 AM3/5/08
to Java EE (J2EE) Programming with Passion!
In C#: Activator.CreateInstance(Type.GetType(class_name)) is used to
create an instance which its class is class_name at run-time. Could
you tell me how to do that in Java. I just know
Class.forName(class_name) is used to return the class. Ex:
I want to create an instance of Customer at runtime. In C#, I do like
that:
Customer a =
(Customer)Activator.CreateInstance(Type.GetType("Customer"));

so in Java, how can I do it???? Thanks so much.

Trung Nguyen

unread,
Mar 5, 2008, 5:05:40 AM3/5/08
to Java EE (J2EE) Programming with Passion!
nobita,

You can use Constructor.newInstance(). For example:

... Class clazz = Class.forName("com.mypackage.MyClass");
... Constructor constructor = clazz.getConstructor(...);
... Object instance = constructor.newInstance(...);

Hope this helps!

Trung Nguyen

Esteban Aliverti

unread,
Mar 5, 2008, 6:14:15 AM3/5/08
to tdn...@gmail.com, Java EE (J2EE) Programming with Passion!
or just:

Object o = Class.forName("com.mypackage.MyClass").newInstance();
 for the empty constructor.


Reply all
Reply to author
Forward
0 new messages