1

say i have this class Framework.Asd.Human with a public empty constructor. and i want to be able to dynamically create an instance of it from a string input "Framework.Asd.Human". Is this achievable? (in java and C#)

Edit:

Is it possible to pass in parameters too? like new Framework.Asd.Human("John", 100, 200); (i know there's no type safety but that's ok in this case)

Kevin LaBranche
  • 20,908
  • 5
  • 52
  • 76
Pacerier
  • 86,231
  • 106
  • 366
  • 634

2 Answers2

2

You can use this overload of the Activator.CreateInstance method:http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

Use it like this:

object myObject = (Framework.Asd.Human)Activator.CreateInstance(TypeOf(Framework.Asd.Human), new object[] { "John", 100, 200 });

And for Java: https://www.cs.auckland.ac.nz/references/java/java1.5/tutorial/reflect/object/arg.html

sventevit
  • 4,766
  • 10
  • 57
  • 89
1

Your going to want to look into reflection.

Check this out for c# and VB.Net - http://msdn.microsoft.com/en-us/library/ms173183.aspx

For Java - http://java.sun.com/developer/technicalArticles/ALT/Reflection/

EDIT

Since you asked about parameters....

c# - http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Java - http://www.java2s.com/Code/Java/Language-Basics/ObjectReflectioninvokeconstructorwithparameters.htm

Kevin LaBranche
  • 20,908
  • 5
  • 52
  • 76