reflection a singleton class?

G

Guest

How to use reflection on a singlton object (i.e. the default constructor is
private)?

I have a configuration file which contains a list of class names. All these
class are simplified singleton type with the similar defintion as below:

public class S
{
private S() {....}

public static S Instance // can be replaced with a method if that makes
things easier
{
get { return _me; }
}
private static S _me = new S();

public void Init() { .....} // do something
};

what I want to do is to invoked the Init() method on all these classes
(whose names are defined in the configuration file).

How can I achieve this? Many thanks in advance for any help and/or thought.
 
N

Nick Malik [Microsoft]

why do you need to call Init on a singleton? initialization should be done
inside the singleton in its constructor.

If you need to call a method on the singleton, you need to get its instance
method to return the object. There is no other way. It should be no
different than calling any other static method.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Xing Zhou said:
How to use reflection on a singlton object (i.e. the default constructor is
private)?

I have a configuration file which contains a list of class names. All these
class are simplified singleton type with the similar defintion as below:

public class S
{
private S() {....}

public static S Instance // can be replaced with a method if that makes
things easier
{
get { return _me; }
}
private static S _me = new S();

public void Init() { .....} // do something
};

what I want to do is to invoked the Init() method on all these classes
(whose names are defined in the configuration file).

How can I achieve this? Many thanks in advance for any help and/or
thought.
 
M

Mattias Sjögren

what I want to do is to invoked the Init() method on all these classes
(whose names are defined in the configuration file).

How can I achieve this?

Something like this

Type.GetType(fullyQualifiedSingletonTypeName).InvokeMember("Init",
BindingFlags.Static | BindingFlags.Public, null, null, null );



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top