Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to a class and execute static method from only a string value?

How can I get an instance of a static class with a string?

Example:

class Apple : IFruit
{
    public static Apple GetInstance() { ... }
    private Apple() { }

    // other stuff
}

class Banana : IFruit
{
    public static Banana GetInstance() { ... }
    private Banana() { }

    // other stuff
}

// Elsewhere in the code...
string fruitIWant = "Apple";
IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();
like image 706
qJake Avatar asked Oct 20 '25 09:10

qJake


1 Answers

Type appleType = Type.GetType("Apple");
MethodInfo methodInfo = appleType.GetMethod(
                            "GetInstance",
                            BindingFlags.Public | BindingFlags.Static
                        );
object appleInstance = methodInfo.Invoke(null, null);

Note that in Type.GetType you need to use the assembly-qualified name.

like image 154
jason Avatar answered Oct 22 '25 23:10

jason