How to dynamically instantiate a class based on a string being the class name???
thanks for reply....
|
Go4Expert Member
|
|
| 24Apr2008,00:09 | #1 |
|
Hi to all expert....
How to dynamically instantiate a class based on a string being the class name??? thanks for reply.... |
|
Go4Expert Founder
|
![]() |
| 24Apr2008,13:13 | #2 |
|
Create the object in a switch case statement when the right string is passed the right object is created.
|
|
Newbie Member
|
|
| 25Apr2008,16:58 | #3 |
|
Quote:
Originally Posted by jakeriggs here is a simple sample code Code:
private void LoadClass()
{
Assembly a = Assembly.GetExecutingAssembly() ;
//create the class base on string
//note : include the namespace and class name (namespace=WindowsFormsApplication1, class name=DynamicLoad)
Object o = a.CreateInstance("WindowsFormsApplication1.DynamicLoad");
//check to see if the class is instantiated or not
if (o != null)
{
Console.WriteLine("Class Loaded");
}
else
{
Console.WriteLine("Failed");
}
}
|
|
Go4Expert Member
|
|
| 30Apr2008,21:24 | #4 |
|
Hi excavator....
thanks for that piece of code...Honestly, I am very new on this.....but I will just study on this code... Thanks again.... |
|
Go4Expert Member
|
|
| 30Apr2008,21:26 | #5 |
|
Hi excavator....
thanks for that piece of code... Honestly, I am very new on this.....but I will just study on it... I will just post follow up question if any..... Thanks again.... |
|
Light Poster
|
|
| 8May2008,23:22 | #6 |
|
Well, although excavator's approuch will work, it isnt very 'clean'.
Why would you want to create a class, based on a string? Where do's that string come from, user input or your own? If its from the user, you really dont want this. They could just execute any code in your application. If you declared that string yourself, consider changing it to an enum, or better yet think of something else. You could for instance use Inheritance, where you have one base class and several depend on it. Thats most likely the way to go. |
|
Newbie Member
|
|
| 7Jul2009,00:16 | #7 |
|
Object ste = Class.forName("java.lang.Integer").newInstance();
|
|
Newbie Member
|
|
| 18May2010,14:37 | #8 |
|
Not sure I agree it's not 'clean' - or that you don't want classes instantiated from user input. An example where I want to do this is when I'm reading a set of commands from a text file - then creating "command" classes based on the text read from each line (which are then queued & processed).
Using the "switch" approach would lead to a huge multi-choice clause which is not elegant. The CreateInstance approach removes the Switch. If I'm thinking along your lines, an enum would require a switch, wouldn't it? Quote:
Originally Posted by CyCloneNL |