Link to home
Start Free TrialLog in
Avatar of BrianMc1958
BrianMc1958

asked on

NEWBIE: Can any method be invoked at class-loading time?

Dear Experts:

I have a MyConstants class, which holds company name, etc.  Everything in it has been defined as public static final.  Now I'd like to add some assignment statements that may as well be static.  Something like initNames below:

public class MyConstants
{
  public static final String[] names;
  public static final int BOB_INDEX = 0;
  public static final int ALICE_INDEX = 2;

  public void initNames()
  {
    names[BOB_INDEX] = "Bob";
    names[ALICE_INDEX] = "Alice";
  }
}
But currently, I never actually instantiate the MyConstants class.  Therefore, even if I put these new assignment statements in the MyConstants class constructor, it does no good--because it never get's constructed.

I have a vague recollection of how to solve this--something about static methods called at class-load time.  Am I making that up?  Is there a way to have this method run (once) without explicitly calling it somewhere?

Thanks!
--BrianMc1958
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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
SOLUTION
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
Avatar of sciuriware
sciuriware

Sorry, answered in parallel ...................................

;JOOP!
Avatar of BrianMc1958

ASKER

I not only can.  I did.  Thanks.  I'd like to point out that my memory in this case was at least in the ballpark--not out wandering around the interstate bypass in it's pajamas like usual.

--BrianMc1958
OK.  I'll respond in parallel.
OK.  I'll respond in parallel.

Personally I tend to write a lot classes with static content (my assembler background?).

Then I give those classes a hidden constructor:

 private MyClass(){ /* Nothing */ }

.. to block faulty instantiation.

I state that this kind of classes is inevitable and right usage.

;JOOP!
gggggggggggggggggggrr! That terrible CEHJ and you type faster than me!


;thanks!
I'm curious, why?  How can instantiation be faulty?  And why would a static block behave differently?
I meant: such a class should not be instantiated at all. Sorry.
:-)