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.
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.
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.
There are mainly three concepts in which we can break the singleton property of a Singleton class in Java.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With