Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a method using reflection on a singleton object

So I have the following:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

Using reflection how can I invoke the DoSomething Method?

Reason I ask is because I store the method names in XML and dynamically create the UI. For example I'm dynamically creating a button and telling it what method to call via reflection when the button is clicked. In some cases it would be DoSomething or in others it would be DoSomethingElse.

like image 930
Crippeoblade Avatar asked Oct 15 '08 12:10

Crippeoblade


People also ask

Can we create instance of singleton class using reflection?

As enums don't give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can't break singleton property in case of enums. Serialization:- Serialization can also cause breakage of singleton property of singleton classes.

How do you call a method of a singleton class?

In a singleton class, when we first-time call the getInstance() method, it creates an object of the class with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object.

How many ways we can break Singleton design pattern?

There are mainly three concepts in which we can break the singleton property of a Singleton class in Java.


1 Answers

Untested, but should work...

string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
    BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
like image 82
Jon Skeet Avatar answered Sep 27 '22 17:09

Jon Skeet