How do I instantiate a class given its string name?
Look at Activator.CreateInstance().
myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName");
or
var type = Type.GetType("MyFullyQualifiedTypeName");
var myObject = (MyAbstractClass)Activator.CreateInstance(type);
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
}
Is there a way to instantiate a class by name in Java?
Two ways:
Method 1 - only for classes having a no-arg constructor
If your class has a no-arg constructor, you can get a Class
object using Class.forName()
and use the newInstance()
method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).
For example:
Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();
Method 2
An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor
object and call a newInstance()
method on this object:
Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);
Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:
- the JVM can't find or can't load your class
- the class you're trying to instantiate doesn't have the right sort of constructors
- the constructor itself threw an exception
- the constructor you're trying to invoke isn't public
- a security manager has been installed and is preventing reflection from occurring
Instantiate a class from its textual name
Here's what the method may look like:
private static object MagicallyCreateInstance(string className)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetTypes()
.First(t => t.Name == className);
return Activator.CreateInstance(type);
}
The code above assumes that:
- you are looking for a class that is in the currently executing assembly (this can be adjusted - just change
assembly
to whatever you need) - there is exactly one class with the name you are looking for in that assembly
- the class has a default constructor
Update:
Here's how to get all the classes that derive from a given class (and are defined in the same assembly):
private static IEnumerable<Type> GetDerivedTypesFor(Type baseType)
{
var assembly = Assembly.GetExecutingAssembly();
return assembly.GetTypes()
.Where(baseType.IsAssignableFrom)
.Where(t => baseType != t);
}
How to instantiate a Class from a String in JavaScript
One possibility is to use eval
.
class Foo {
constructor() {
console.log('Foo!');
}
};
const foo = 'Foo';
const bar = eval(`new ${foo}()`);
console.log(bar);
How to instantiate class by it's string name in Python from CURRENT file?
If you are on the same module they are defined you can call globals()
, and simply use the class name as key on the returned dictionary:
Ex. mymodule.py
class A: ...
class B: ...
class C: ...
def factory(classname):
cls = globals()[classname]
return cls()
Above solution will also work if you are importing class from another file
Otherwise, you can simply import the module itself inside your functions, and use getattr (the advantage of this is that you can refactor this factory function to any other module with no changes):
def factory(classname):
from myproject import mymodule
cls = getattr(mymodule, classname)
return cls()
Java how to instantiate a class from string
"Using java.lang.reflect
" will answer all your questions. First fetch the Class
object using Class.forName()
, and then:
If I want to instantiate a class that I retrieved with
forName()
, I have to first ask it for ajava.lang.reflect.Constructor
object representing the constructor I want, and then ask thatConstructor
to make a new object. The methodgetConstructor(Class[] parameterTypes)
inClass
will retrieve aConstructor
; I can then use thatConstructor
by calling its methodnewInstance(Object[] parameters)
:Class myClass = Class.forName("MyClass");
Class[] types = {Double.TYPE, this.getClass()};
Constructor constructor = myClass.getConstructor(types);
Object[] parameters = {new Double(0), this};
Object instanceOfMyClass = constructor.newInstance(parameters);
There is a newInstance()
method on Class
that might seem to do what you want. Do not use it. It silently converts checked exceptions to unchecked exceptions.
Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The
Constructor.newInstance
method avoids this problem by wrapping any exception thrown by the constructor in a (checked)InvocationTargetException
.
Using a string to instantiate a class
I'm not sure I understand correctly, seems weird no one else mentioned this yet:
Map<Character, ShapeFactory> dict = new HashMap<>();
dict.put('C', new CircleFactory());
dict.put('R', new RectangleFactory());
dict.put('T', new TriangleFactory());
...
ShapeFactory factory = dict.get(symbol);
Shape shape = factory.create(data);
Instantiate object from class name as string
You can create an instance of a class and run its methods without ever having to import the class in your code using reflection:
Class clazz = Class.forName("com.whatever.MyClass");
Object instance = clazz.newInstance(); // or use the given instance
clazz.getMethod("myMethod").invoke(instance);
Related Topics
How Do Prefix (++X) and Postfix (X++) Operations Work
Difference Between Registerstartupscript and Registerclientscriptblock
Get All Inherited Classes of an Abstract Class
Is the Use of Dynamic Considered a Bad Practice
Onclientclick and Onclick Is Not Working at the Same Time
Frombody String Parameter Is Giving Null
Which Version of C# am I Using
Sharing Memory Between Two Applications
Accessing MVC's Model Property from JavaScript
Views in Separate Assemblies in ASP.NET MVC
Find a String Between 2 Known Values
Why Use Icollection and Not Ienumerable or List<T> on Many-Many/One-Many Relationships
Multipart Forms from C# Client
How to Get Values of Selected Items in Checkboxlist with Foreach in ASP.NET C#
Why Does the Equals Implementation for Anonymous Types Compare Fields