Create an instance of a class from a string
Take a look at the Activator.CreateInstance method.
C# Instantiate a Class from String name
This technical called Reflection, that means call an instance from string.
My calling class will be
public class Class1
{
public string Property { get; set; } = "I'm class1";
public void DoSpecialThings()
{
Console.WriteLine("Class1 does special things");
}
}
Next I create an instance in a static function, should put your all classes in a same namespace to easy control
public static dynamic GetClassFromString(string className)
{
var classAddress = $"NetCoreScripts.{className}";
Type type = GetType(classAddress);
// Check whether the class is existed?
if (type == null)
return null;
// Then create an instance
object instance = Activator.CreateInstance(type);
return instance;
}
And a GetType method
public static Type GetType(string strFullyQualifiedName)
{
Type type = Type.GetType(strFullyQualifiedName);
if (type != null)
return type;
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
type = asm.GetType(strFullyQualifiedName);
if (type != null)
return type;
}
return null;
}
I use dynamic type to implement quickly, basically you can use interface for explicit coding.
static async Task Main(string[] args)
{
dynamic instance = GetClassFromString("Class1");
Console.WriteLine(instance.GetType().FullName); //NetCoreScripts.Class1
Console.WriteLine(instance.GetType().Name); //Class1
Console.WriteLine(instance.Property); //I'm class1
instance.Property = "Class1 has been changed";
Console.WriteLine(instance.Property); //Class1 has been changed
instance.DoSpecialThings(); // Class1 does special things
}
Create instance of class and call method from string
// Find a type you want to instantiate: you need to know the assembly it's in for it, we assume that all is is one assembly for simplicity
// You should be careful, because ClassName should be full name, which means it should include all the namespaces, like "ConsoleApplication.MyClass"
// Not just "MyClass"
Type type = Assembly.GetExecutingAssembly().GetType(ClassName);
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get MethodInfo, reflection class that is responsible for storing all relevant information about one method that type defines
MethodInfo method = type.GetMethod(MethodName);
// I've assumed that method we want to call is declared like this
// public void MyMethod() { ... }
// So we pass an instance to call it on and empty parameter list
method.Invoke(instance, new object[0]);
Create object instance of a class having its name in string variable
Having the class name in string is not enough to be able to create its instance.
As a matter of fact you will need full namespace including class name to create an object.
Assuming you have the following:
string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";
Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass
using either of the following techniques:
var myObj = Activator.CreateInstance(namespaceName, className);
or this:
var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));
Hope this helps, please let me know if not.
How to create an instance of a class from a String in Swift
You can try this:
func classFromString(_ className: String) -> AnyClass! {
/// get namespace
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
/// get 'anyClass' with classname and namespace
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!
// return AnyClass!
return cls
}
use the func like this:
class customClass: UITableView {}
let myclass = classFromString("customClass") as! UITableView.Type
let instance = myclass.init()
Creating an instance from String in Java
Class c= Class.forName(className);
return c.getDeclaredConstructor().newInstance();//assuming you aren't worried about constructor .
- javadoc
For invoking constructor with argument
public static Object createObject(Constructor constructor,
Object[] arguments) {
System.out.println("Constructor: " + constructor.toString());
Object object = null;
try {
object = constructor.newInstance(arguments);
System.out.println("Object: " + object.toString());
return object;
} catch (InstantiationException e) {
//handle it
} catch (IllegalAccessException e) {
//handle it
} catch (IllegalArgumentException e) {
//handle it
} catch (InvocationTargetException e) {
//handle it
}
return object;
}
}
have a look
Create class instance from string in dartlang
For passing arguments dynamically to the constructor you can use newInstance
method of ClassMirror
.
For example
MirrorSystem mirrors = currentMirrorSystem();
ClassMirror classMirror = mirrors.findLibrary(Symbol.empty).declarations[new Symbol('Opacity')];
print(classMirror);
var arguments = {'a': 'a', 'b': 'b', 'c': 'c'}.map((key, value) {
return MapEntry(Symbol(key), value);
});
var op = classMirror.newInstance(Symbol.empty, [], arguments);
Opacity opacity = op.reflectee;
print("opacity.a: ${opacity.a}");
print("opacity.b: ${opacity.b}");
print("opacity.c: ${opacity.c}");
Related Topics
Understanding Garbage Collection in .Net
How to Enable Assembly Bind Failure Logging (Fusion) in .Net
Linq'S Distinct() on a Particular Property
How to Call Asynchronous Method from Synchronous Method in C#
What Is the Correct Way to Create a Single-Instance Wpf Application
What Are the Differences Between a Multidimensional Array and an Array of Arrays in C#
Fastest Way of Inserting in Entity Framework
Collection Was Modified; Enumeration Operation May Not Execute
Is There a Constraint That Restricts My Generic Method to Numeric Types
Convert a String to an Enum in C#
How to Add User-Supplied Input to an SQL Statement
Windows Service Not Shown in Add Remove Programs Under Control Panel
Send Http Post Request in .Net
How to Do a Deep Copy of an Object in .Net
Difference Between the | and || or Operators
How to Load Dll (Module Could Not Be Found Hresult: 0X8007007E)