How to reference a static variable before the static initializer runs

I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
public class Foo  {
  public static final SumClass fooVar;  // by default initialized to null
  static  {
     fooVar = new SumClass();
public class Bar  {
  public static final SumClass barVar;
  static  {
     barVar = Foo.fooVar;  // <<<--- set to null !
}Warning: Speculation ahead.
Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
public class Foo  {
  public static final SumClass fooVar = new SumClass();  // either this ..
public class Bar  {
  public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
}But there are times when you need to use it.
So what's an elegant way to avoid the problem?

DMF. wrote:
jschell wrote:
But there are times when you need to use it. I seriously doubt that.
I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
What? You only encounter those once in a career? We must have very different careers. ;)
So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

Similar Messages

  • How can I pass environment variables to the child process?

    How can I pass environment variables to the child process? This is what I tried and it didn't work.
         static public void main (String[] args) throws Exception {
              ProcessBuilder b = new ProcessBuilder("java", "-cp", ".", "Child");
              Map<String, String> map = b.environment();
              map.put("custom.property", "my value");
                 b.redirectErrorStream(true);
              Process p = b.start();
              BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream()));
              String line = null;
              while (null != (line = reader.readLine())) {
                   System.out.println(line);
         public static void main(String[] args) {
              System.out.println("The value of custom.property is : " + System.getProperty("custom.property"));
         }and the result is:
    The value of custom.property is : null

    Complete test:
         static public void main (String[] args) throws Exception {
              ProcessBuilder b = new ProcessBuilder("java", "-Dcustom.property=my property value", "-cp", ".", "Child");
              Map<String, String> map = b.environment();
              map.put("custom.property", "my environment value");
                 b.redirectErrorStream(true);
              Process p = b.start();
              BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream()));
              String line = null;
              while (null != (line = reader.readLine())) {
                   System.out.println(line);
         public static void main(String[] args) {
              System.out.println("Property value of custom.property is : " + System.getProperty("custom.property"));
              System.out.println("Environment value of custom.property is : " + System.getenv("custom.property"));          
         }

  • How do I set a variable on the main timeline from within a symbol?

    Just getting started with Animate and coming to it from Flash, as may be apparent from my question. How do you set a variable to the main timeline from within a symbol?
    I have 24 pairs of clickable elements, each in their own symbols, and all 24 of those symbols sit inside another symbol. I want all 24 to be able to set the same global variable when clicked. I can't find that this question is addressed anywhere, which makes me think I may be stuck in a Flash mindset and approaching the task in the wrong way. (There are however MANY discussions of how to address objects at different levels in the hierarchy. That's well covered.)
    Relatedly, how do you access a function on the main timeline from within a symbol?
    Adobe should consider putting together a support page (or pages) just for folks migrating form Flash. In the materials I've encountered so far there seems to be a studied effort to refrain from mentioning Flash in any way. I imagine there are a lot of people out there like me who have a deep background in Flash coding, but are just getting started with Animate. We don't need help with most of the basic concepts, but we may still have some pretty basic questions about how to accomplish some things in Animate because our Flash knowledge is getting in the way.

    Hi Bill,
    There are plenty of threads on here about scope, but here's one way to create a global variable:
    // code on Stage.compositionReady
    sym.myGlobalVar = 1;
    Then, anywhere in your project, you can check/set that var like so:
    sym.getComposition().getStage().myGlobalVar = 2;
    And here's one way to create a global function:
    // code on Stage.compositionReady
    sym.myGlobalFunction = function(){
              console.log('myGlobalFunction');
    Then, anywhere in your project, you can call that function like so:
    sym.getComposition().getStage().myGlobalFunction();

  • ABAP program to add in the process chain before the attribute change run

    Hi
    I need a ABAP program to add in the process chain before the attribute change run(process) to avoid the locks, can any one send me the program
    Regards,
    Satish

    I am not sure of any standard program .... but you can write your own... should be a small one..
    you can check if the table RSDMDENQ has entry for your InfoObject... if yes, then its locked.. if not.. its not locked

  • How do i make is so that the program is running already and then have a start button to execute?

    I created a program to control a function generator.  I want it so that the program is already running when i load it up, and then when i actually want it to run press a start button.   I think you can just do a case structure for the start button... but how do i get it so that the program is running when you load it.  so when you press the start button it starts. instead of having to press the start button, then press the run program button. thanks!

    A few things about Run When Opened.  Once this is set, if you need to edit the vi, it will start running when you open it.  You then have to abort the vi to edit it.  Some people like to make a backup copy that is not set to run when opened so they can edit it without the hassle of aborting.  In your case, it is probably not worth it since your vi does nothing until the start button is pressed.  But this is for future instances of run when opened.  Also, if you want to edit, I think if you press and hold the shift key (or is it the control key) while opening the vi, it will not run when opened.  Another method to get around the run when opened is to create a blank vi.  In the block diagram, put your vi that is set to run when opened.  Then you can double click on the vi and edit it without having it run when opened.
    - tbob
    Inventor of the WORM Global

  • How can i reload font information while the jvm is running.

    l.s.
    how can i reload font information while the jvm is running.
    I'm having the following problem...
    A program is running.
    A user installs a new font on the system (Xwindows in this case)
    Java doesn't display the font when i ask :
    java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();Thus i think that java buffers its font information somewhere. Anyone knows how to refresh te buffer?
    many thanks

    ungalcrys, welcome to the forum. Please don't post in threads that are long dead and don't hijack another poster's thread. When you have a question, start your own topic. Feel free to provide a link to an old post that may be relevant to your problem.
    I'm locking this thread now.
    db

  • How can i "find my iphone" if the charge has run out so the "lost phone" can't be ONLINE?

    How can I "Find my iphone" if the charge has run out so the phone that is lost can't be ONLINE?

    You can't.  Place it in lost mode and it will be implemented if and when the lost device is recharged by someone and connects to the internet.

  • How to set a bind variable across the pages in a report

    I want to create a portal report where data will come from a table for a date range for a week.
    For e.g select event_date,last_name, event_name
    from RESOURCES
    where event_date between trunc(to_date(:curr_date,'DD-MON-RRRR'))
    and trunc(to_date(:curr_date,'DD-MON-RRRR')+ 7)
    The :curr_date is defined as a bind variable whose default value is sysdate.
    Now, when we run the report for the first time, it takes the :curr_date as
    sysdate and prints the report.
    I have two buttons in the report output like "previous week" and "next week".
    If someone presses previous week, the same report should run with curr_date
    as sysdate-7 and if someone presses next week, the report should run with
    curr_date as sysdate +7 and also the :curr_date sets to sysdate - 7 or sysdate + 7
    depending on the button pressed.
    Problem:
    How do I set the value of curr_date if someone presses any of
    previous week/next week.
    null

    Best to state your JDev version, and technology stack (eg. ADF BC) when posting.
    I can think of 2 approaches.
    1) Create a parent VO based on SELECT :bindVar FROM dual, then create links between your other VOs and the parent
    2) Create a AM client interface method that programatically sets the bind variable in each VO.
    Can you specify your use case? This one tends to come up when discussing effective from/to dated queries.
    CM.

  • How to put a javascript  variable containg the i18n key  in the i18n tag

    I have a list of values in a List box.when the user selects a praticular value.,i need to show the java script localized alert message for the selected value.
    how can i pass the javascript variable to i18n tag.
    For ex:
    function test(){
    var selectedvalue='name';
    var localizedstring='<i18n:message key="+selectedvalue+"/>';--This is not working
    alert('<i18n:message key="+selectedvalue+"/>');
    the alert message is a blank string,even though i have the key in my resource bundle.
    Also..if i give directly pass the key value to i18n string it works. like..
    var localizedstring='<i18n:message key="+name+"/>';--This is  working
    *(am passing the variable value)*

    The following should be able to pass ans.
    <script language="Javascript">
    function check_answer(ans) {
    if (testing.result.value==ans ){
    window.alert("You have got 10 marks.");
    </script>
    <body>
    <form name="testing"...>
    <%
    ResultSet rs = stmt.executeQuery("select * from level where...");
    while(rs.next())
    out.println("<tr>");
    out.println("<td>" + rs.getString("question") + "</td>");
    ans = rs.getString("answer");
    out.println("</tr>");
    out.println("<input type='text' name='result'>);
    out.println("<input type='button' value='Enter' onclick='check_answer('<%= ans%>')'>");
    %>jag

  • How to use customer exit variable in the report

    Dear All,
    i want to use a standard customer exit variable in the report properties.
    In the Bex Query Designer right hand bottom you will find two buttons "Properties" and "Task". Click on task you will get different option. Choose properties from there and then select "variable sequence tab".
    I need to add a standard variable there. How can i achieve it?
    Appreciate your early help.

    You need to add variable to corresponding charctertic then you can get that varaible for sorting the sequence....
    If 0CUST is the varaible then you need to assign it 0CUSTOMER then 0CUST will be available for the sequence.
    Edited by: shanthi bhaskar on Apr 2, 2009 5:41 PM

  • How to print a request variable in the name of a section?

    Hello all,
    I have a session variable created in the RPD called VarWorstStore
    and I have a prompt which sets a request variable with the same name.
    Now when I put a report which is filtered on this variable then I can see that the variable is changing when I press go in the dashboard prompt.
    However, I call this variable in a section as well (go to page options - edit dashboard and click on rename of a section)
    Now I type: @{biServer.variables['NQ_SESSION.VarWorstStore']} and check the box Display section heading.
    Now when I save the dashboard I can see the value of the session variable. However, when I change the session variable with the prompt, thenb I can see that the report is changing, but the title isn't.
    Can anyone help me on this? My reference on this was: http://4.bp.blogspot.com/_f689sAiiG-E/SKv8Fxu7wNI/AAAAAAAAAPk/pppwQ1DdEhg/s1600-h/obi-ee-variables-overview.jpg
    I think it is a bug, but perhaps someone knows
    OBIEE version:
    Build: 10.1.3.4.1.090414.1900
    Release Version: Oracle Business Intelligence 10.1.3.4.1
    Package: 090414.1900

    Thanks for all your responds!!
    However, I was thinking in first instance on a narrative view myself indeed, however this is not good enough for me, because I really have an almost pixel perfect dashboard.
    But the thing with the prompt works!!! What I have done is making an extra prompt with the default value set to the session variable and then I set a presentation variable in the same prompt, and after that I am filtering the reports on the presentation variable in stead of the session variable.
    But I cannot find anywhere where to hide the prompt, can you tell me this?
    The only way I can hide things is to set permissions I gues, but then I also guess is that the prompt will do not do its tasks when the user has no permissions to this prompt.
    Hope you can help me out on this last part!!

  • Pleasanton store always overcrowded and noisy. They no longer offer one hour one on one intro session. I can't hear or think with all the commotion in the store.  How can I get an appt. before the store opens?

    The Pleasanton store is always overcrowded and noisy. I can't hear and can hardly think in there. They no longer offer a 1 hr. one on one intro session. I want to buy a mac this week but I won't if I can't try one and get my questions answered. How can I get an intro session before the store opens?

    If you know which computer you want you can order it online at the online Apple Store. As for learning your new computer Apple provides many online tutorials for people make the switch from a PC. Here are some starter sites that I'd recommend you bookmark and use.
    Switch 101, Mac 101 & Find Out How Video tutorials.
    If you prefer to purchase directly from a brick and mortar Apple Store you are very fortunate to live in the Bay Area, where there are many stores to choose from. When you arrive tell the receptionist you want to purchase an iMac and they will have help you get a sales professional to help you. You can also use the new system Apple implemented this past week at any of the display counters to request a sales person come to you. Again the receptionist can help you get started on that too. Once a system is purchased and you buy the one on one service the one one one service is executed where it's more quiet than inside the store. I frequent the Valley Fair store in Santa Clara on occasion, this store is extremely busy and I see people receiving one on one service all the time within the mall at dedicated tables.
    Roger 

  • How to post Unplanned Delivery Cost before the actual invoice

    Hello Experts
    Our client has a scenario when they received the unplanned Delivery cost before the actual invoice of that purchase.
    We are handling the Unplanned Delivery cost by entering on the header level on the regular scenario.
    Can somebody give there exert thought how we handle the Unplanned Delivery Cost Invoice before the actual Invoice.

    Hello,
    It is a process issue and I have seen similar situtations. Here is a possible solution.
    1. You should estimate the standard freight and put this as part of Material Cost.
        This can be a condition type or it can come from PIR, depending upon how you
        calculate the material cost.
    2. At the purchasing level, add a condition type for Freight. So, at the time of GR,
        system will automatically accrue the freight amount. This will be based on the
        esitmated amount and not the actual amount. You can capture the offset  
        account in a separate accrued freight payable account.
    3. At the time of processing the actual freight invoice, debit the accrued freight
       payable account.
    4. On regular basis watch your estimated and actual freight expenses and make  
        necessary adjustments.
    Hope this helps.

  • HT4910 how to refund my iCloud purchase before the 15 ends & whats the correct adress or link used for that

    How to refund my iCloud purchase bill before the 15 ends & whats the correct adress or link used for that

    See Roger's post here: https://discussions.apple.com/thread/4671693?start=0&tstart=0.

  • How to deal with .csproj.user being created/modified by Visual Studio before the project is run?

    So, what is the problem?
    The problem is that Visual Studio considers .csproj.user a dependency of the project being run.
    Let us assume the following:
     - We have a freshly built solution containing a web application project `X` as the Start Up project. 
     - There are Silverlight applications served by the X web application.
     - There is no `X.csproj.user` file initially.
    Now consider the following flow of events:
     1. Open the solution in the Visual Studio
     2. Build.
     3. Run.
     4. A dialog is open to ask whether Silverlight debugging is to be enabled. Enable it.
     5. Stop the debugging session.
     6. Run again.
     7. Stop the debugging session.
     8. Run again.
    Assuming nothing is built at step 2 (because the solution is totally up to date), will there anything be built at steps 3 and 6?
    The answer is affirmative and here is why:
     - The X.csproj.user file is actually created by Visual Studio when the project is requested to run. What happens next is that the
    X.csproj.user file is considered a dependency of the project
    X by the Visual Studio. Being created just now the file is newer than the project binaries and so Visual Studio builds the project
    X. This explains why the project is built at step 3.
     - When we agree to enable Silverlight debugging Visual Studio records this agreement in the
    X.csproj.user file. So the file is modified again, after the project has started running. Restarting the debugging session is going to build the project
    X yet again, after all X.csproj.user is again newer than the binaries built a second ago. This explains why the project is built at step 6.
    Fortunately, nothing is built at step 8.
    Call me petty, but I want to avoid the builds at steps 3 and 6. The problem is that I am not allowed to check in the X.csproj.user file, because that is likely to create a mess with people accidentally checking in their private changes.
    On the other hand, I am unable to move its default content (along with the agreement to enable Silverlight debugging) into the project file
    X.csproj. Well, I can, but it is just being ignored.
    So, here is my question - is it possible to separate the content stored in a
    .csproj.user into two groups:
     - Permanent. These are the things I would love to have in the .csproj file. It will be checked in.
     - Temporary/Private. These are the things private to individual developers. Never checked in.
    Visual Studio already allows this separation for certain properties - see the
    Apply server settings to all users (store in project file) checkbox in the Web properties tab of a Web application project - http://olalalittlen.wordpress.com/2011/07/20/vs-tips-managing-server-settings-in-web-projects-for-multi-developer-scenarios/.
    However, it is insufficient.
    Any other ideas on how to prevent the aforementioned redundant builds are welcome too.

    Hi Mark,
    I think your issue is more about project itself. the saved information in the .csproj.user settings is about the project's information.
    So I suggest you post your issue to the related project forum.
    web forms:http://forums.asp.net/18.aspx/1?Web+Forms
    mvc:http://forums.asp.net/1146.aspx/1?MVC
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • How to retrieve Hidden ABAP program code

    Hi All, If a ABAP Source code is hidden by some special charaters or some other report. is there any way to retrieve the same. thanks Alexander

  • IBM Endpoint Manager / BigFix Versus System Center Configuration Manager

    Hi All, My organization's security team (which I'm not on) has been tasked with researching patching solutions for our environment which includes mostly Windows workstations but a good amount of Linux systems as well. Total amount of workstations cov

  • CS6 color swatch creation

    Seems as though there is an issue with CS6 Adobe Illustrator color swatch creation. I created a swatch based on RGB values and then saved it as a spot color. When creating a new file and using that swatch the fill color doesnt match. Everything is on

  • Anyone experiencing extremely slow downloads from Apple?

    For the past 48hrs or so I've been unable to stream or download HD Video from iTunes store or iCloud on any of my devices, Apple TV's or Computers. Netflix, Amazon Prime, and other HD Streaming services unaffected.  Internet up and running 45Mbps con

  • No Picture MMS on 3GS after update to 4.0 software

    After I updated my 3GS to the 4.0 software, I lost the ability to send picture messages. If you know how to fix this, please let me know what I have to do!