Link to home
Start Free TrialLog in
Avatar of realman1
realman1

asked on

How to know I already load a class?

I have one application that will call up many class. But every class is only allow to be start once.

How to detect whether a class is running?

Guys, any idea?
Avatar of girionis
girionis
Flag of Greece image

 You mean load it only once? What you can do is to maintain a hashtable of classes and when asked return the *exact* class object reference. You will have to check the Hashtable every time a class is requested in order to see if it is already there or not. If it is return it, otherwise load it and put it in the hashtable.

  The following might come in handy: http://www.javaworld.com/javaworld/jw-10-1996/jw-10-indepth.html

  Hope it helps.
Realman.

Pls refer to the documentation for ClassLoader and it has method called findLoadedClass() which returns class or null if it is not loaded in the memory.

Thanks
Shyam
Avatar of BaneBane
BaneBane

Why don't you use the singletone design pattern. this pattern alows for only one instance of a class to be loaded.

I'v included a sample code.

class x{

   private X m_Instance = null;

   /**
    private constructor, thus it can not be called.
   */  
   private x(){
   }
   
   public synchronized X getInstance(){
     if (m_Instance==null)
        m_Instance = new x();

     return m_Instance;
   }
}


Hope this helps.
bane
Pls don't lock the question. Just put ur info on comments still comments can be choosen as solution

Cheers
SHyam
opps sorry, I'm new to this
 BaneBane please do not propose answers, only comments instead, as this locks the question and it is difficult for other people to give an answer.

  Thank you.
 OOps sorry, I did not see shyamkumarreddy's comment.
Thanks for taking advice Bane. Even i did this mistake when i am new to this society. Always keep learning things :)

Shyam
again sorry
... or if you create these classes, you can use static initialization:

class MyClass() {
  private static boolean started = false;
 
  ...
 
  public void start() {
    if (started) return;
   
    started = true;
    ...
  }
}
ASKER CERTIFIED SOLUTION
Avatar of Ovi
Ovi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
...optimization :

  public static final Object getInstance(String className) {
    Object o = instances.get(className);
    return((o != null)?o:createInstance(className));
  }

Avatar of realman1

ASKER

Ovi help will be more suitable for my application.
Anyway, thank you guys. :)
I will go for second choice. :)
I will go for the second one. :)