Instantiate Class from Name

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

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 a java.lang.reflect.Constructor object representing the constructor I want, and then ask that Constructor to make a new object. The method getConstructor(Class[] parameterTypes) in Class will retrieve a Constructor; I can then use that Constructor by calling its method newInstance(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.

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);
}

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);

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()

Instantiate class from name?

This is a problem which is commonly solved using the Registry Pattern:

This is the situation that the
Registry Pattern describes:

Objects need to contact another
object, knowing only the object’s name
or the name of the service it
provides, but not how to contact it.
Provide a service that takes the name
of an object, service or role and
returns a remote proxy that
encapsulates the knowledge of how to
contact the named object.


It’s the same basic publish/find model
that forms the basis of a Service
Oriented Architecture (SOA) and for
the services layer in OSGi.

You implement a registry normally using a singleton object, the singleton object is informed at compile time or at startup time the names of the objects, and the way to construct them. Then you can use it to create the object on demand.

For example:

template<class T>
class Registry
{
typedef boost::function0<T *> Creator;
typedef std::map<std::string, Creator> Creators;
Creators _creators;

public:
void register(const std::string &className, const Creator &creator);
T *create(const std::string &className);
}

You register the names of the objects and the creation functions like so:

Registry<I> registry;
registry.register("MyClass", &MyClass::Creator);

std::auto_ptr<T> myT(registry.create("MyClass"));

We might then simplify this with clever macros to enable it to be done at compile time. ATL uses the Registry Pattern for CoClasses which can be created at runtime by name - the registration is as simple as using something like the following code:

OBJECT_ENTRY_AUTO(someClassID, SomeClassName);

This macro is placed in your header file somewhere, magic causes it to be registered with the singleton at the time the COM server is started.

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
}

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);


Related Topics



Leave a reply



Submit