Can You Use a String to Instantiate a Class

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.

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

Can you use a string to instantiate a class?

Not sure this is what you want but it seems like a more Pythonic way to instantiate a bunch of classes listed in a string:

class idClasses:
class ID12345:pass
class ID01234:pass
# could also be: import idClasses

class ProcessDirector:
def __init__(self):
self.allClasses = []

def construct(self, builderName):
targetClass = getattr(idClasses, builderName)
instance = targetClass()
self.allClasses.append(instance)

IDS = ["ID12345", "ID01234"]

director = ProcessDirector()
for id in IDS:
director.construct(id)

print director.allClasses
# [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>]

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

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 Kotlin class from string

Instantiating classes by String name is more error-prone than using a constructor, because it relies on using a fully qualified, correctly spelled name, and the class having a specific constructor (either empty, or with specific arguments). So it can be done, but should be avoided when there are safer ways of doing it (ways where the compiler will give you an error if you're doing it wrong, instead of having an error occur only after you run the compiled program).

If I understand correctly, you want a list of classes that will only be instantiated one-at-a-time at random. One way to do this would be to make a list of class constructors.

val classConstructors = listOf<() -> Any>(
::ClassA,
::ClassB,
::ClassC
)

val randomInstantiatedClass = classConstructors.random()()

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
}

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



Leave a reply



Submit