How to ensure multiple nested classes static readonly initialization orders

Hello,
I am emulating the Java Enumeration in a first class class, with static readonly field initialization.
In an effort to further categorize some instances, I embed them in nested classes. Something like this.
class A : Enumeration
public static class CatB
public static readonly A FirstInstance = new B();
public static readonly A SecondInstance = new B();
public static class CatC
public static readonly A ThirdInstance = new C();
public static readonly A FourthInstance = new C();
class B : A
class C : A
So far so good.
One strain of Enumeration has built-in Ordinals, so I initialize them in the static ctor, or I make an effort to.
static A()
var values = GetValues().ToList();
var ordinal = 0;
values.ForEach(v => v.Ordinal = ++ordinal);
Also, in places, so far so good.
However, in a main method, I am referencing one of the enumerated instances, so calls to my GetValues() is returning nulls for that nested class. The other nested class instances are just fine, they return just fine.
I could post more, but I think this illustrates the idea.
I am suspicious that a strange static initialization order is jumbled up, as evidenced by nested static ctor debug statements I put in. I get one print and not the other.
When I switch up which instance I reference in my main, I get the opposite behavior, more or less confirming my suspicions.
So... Question is, what's the best way to potentially work around this issue? Hopefully without abandoning the Enumeration concern altogether, but that thought is a possibility as well. Or at least do so differently.
Thank you...

It is probably necessary to show GetValues() at least. I am getting the correct nested types, so that much we can at least assume.
protected static IEnumerable<TDerived> GetValues()
var declaringTypes = GetDeclaringTypes(typeof (TDerived)).ToArray();
foreach (var declaringType in declaringTypes.Reverse())
var fis = declaringType.GetFields(PublicStaticDeclaredOnly);
var values = fis.Select(fi => fi.GetValue(null)).ToArray();
foreach (var value in values.OfType<TDerived>())
yield return value;
Okay, here a bit of explanation.
Enumeration is declared generically, with TDerived as the derived type. In this case, A.
GetDeclaringTypes is operating okay. I get types for A, B, and C.
The fis to values is breaking down, however. When I reference any of the CatB's, I get nulls for those instances. Conversely, same for CatC's when I reference any of those.

Similar Messages

  • How to assign multiple batch class to material in classification view

    Dear Gurus,
    How to assign multiple batch class to material in classification view.
    plz explain what are the procedure and what are the configuration required before assignment.
    Thanks
    Mani

    OK, Thanks for your reply.
    Regards
    Mani

  • How to override a nested class?

    I'm relatively new to Java, so this may be an easy question, but how do you override the behaviour of a nested class when extending a parent class? For example:
    public class MyParentClass
      public class MyParentNestedClass
        public void someMethod()
          // Some functionality that I want to change 
    }Now I want to create a new class, let's call it MyChildClass, which extends MyParentClass and changes the behaviour of the inner class. Is this possible? What is the syntax to accomplish this? Are there any scope-related problems I should be aware of?
    Do I have to extend the parent class in order to redefine the nested class, or is there some way to just override the nested class (which is all I really want to change)? Any help on this would be appreciated, I've searched both the Sun site and Google and can't come up with a really clear answer to this one.
    Thanks,
    Steve

    That's exactly what I was after. I was trying to do it like this:
    public class MyChildClass extends MyParentClass
      MyParentNestedClass childNestedClass = new MyParentNestedClass()
        public void someMethod() { /* new functionality */ }
    }because I have seen anonymous classes (I think they're called adapter classes) declared like this, but it wasn't working in this case. Thanks for showing me the correct way to do it, I guess in retrospect that makes perfect sense, I don't know why I didn't think of it.
    Thanks,
    Steve

  • How to @see a Nested Class

    package mappackage;
    public class MyMap {
         * Displays the map's legend.
         * @see MyMap.MapLegend
        public void displayLegend() {
            new MapLegend();
        class MapLegend {
            //some code and vars here
    }The above is what I have right now, basically. My problem is that javadoc cannot find MapLegend, and I have tried some logical guesses:
    - @see MapLegend
    - @see MyMap.MapLegend
    - @see mappackage.MyMap.MapLegend
    ...and then other random things like...
    - @see #MapLegend
    - @see MyMap#MapLegend
    - @see this.MapLegend
    ...I was getting frustrated and desparate.
    I was able to @link to MapLegend from another file in the same package by saying MyMap.MapLegend, but I cannot @see my own nested class? That is really annoying. Any ideas?

    Hi Syrae,
    I just tried @see MapLegend and it worked for me. The problem with your code is that you are trying to link to something that is not visible. If you declare your nested class as public or run javadoc with the -private option, your link should work.
    -Jamie

  • How to Create Multiple Sources/Classes with one Script

    I am trying to get all of my java sources, or classes, into one script so that I can move them all to another server without having to compile each file individually. When I concatenate two files and try to compile I get an ORA-29536: badly formed source error.
    How can I get multiple definitions into one file and compile all of the classes?
    Thanks,
    Gregory

    Gregory:
    If you want to upload several Java classes in one script the solution is .sql file, for example:
    set define ?
    create or replace and compile java source named "my.Sleep" as
    package my;
    import java.lang.Thread;
    public class Sleep {
    public static void main(String []args) throws java.lang.InterruptedException {
    if (args != null && args.length>0) {
    int s = Integer.parseInt(args[0]);
    Thread.sleep(s*1000);
    } else
    Thread.sleep(1000);
    create or replace and compile java source named "my.App" as
    package my;
    public class App {
    public static void main(String []args) throws java.lang.InterruptedException {
    System.out.println(args[0]);
    exit
    Then the .sql file can be parsed using the SQLPlus, JDeveloper or SQLDeveloper tools.
    HTH, Marcelo.

  • How to import multiple, nested directories?

    I have a directory structure of all my old images, going back to 2002. The top folder has 2002, 2003, ...up to 2009. In each of these folders, there are 12 folders for each month, and in each monthly folder, there are folders for each day, and in those, all the images (some raw but mainly jpeg).
    I am trying to figure how to import them into Aperture. So far, all I can find is that I can select each days folder and it will grab all the images in that folder. But, this method will force me to import up to 2,000 folders.
    I would like to find a way to import and have it select all folders recursively down the chain.
    For now, I am going to just reference the images, and maybe start moving to a managed library over time. Any thoughts to watch out for in that thinking?
    Jeff

    Nevermind, I just found it....Import projects into folders from the menu.

  • How to handle multiple SOAP requests for ArrayCollection initialization?

    Hello.
    I want to initialize some ArrayCollection with objects, which receive field values via SOAP requests (in getUdfValuePrj function).
    for (var i:int=0; i < data.length; i++)
      var task:Task=new Task();
      task.laborio = getUdfValuePrj(data[i].id, LABORIOUSNESS);
    tempTaskArray.addItem(task);
    Here is my WebService:
    private function initWebServices(wsdl:String):void
      _udfWs = new WebService();
      _udfWs.wsdl = wsdl;
      _udfWs.getTaskUDFValue.addEventListener("result",
      getTaskUDFValueResult);
      _udfWs.getTaskUDFValue.addEventListener("fault", handleFault);
      _udfWs.loadWSDL();
    The question is, how functions getUdfValuePrj and getTaskUDFValueResult should look like?
    I think that is no good:
    private function getTaskUDFValueResult(event:ResultEvent):String
      _udfValue = event.result as String;
    private function getUdfValuePrj (taskId:String, udfCaption:String):String
      _udfValue = "Loading...";
      _udfWs.getTaskUDFValue (taskId,udfCaption);
      while (_udfValue == "Loading...")
      return _udfValue;

    There is no any ideas, or may be you don't understand me?

  • Cloning nested classes

    Does anyone know where I can get information on how
    clone() behaves with nested classes? thanks ...

    I'm actually talking about nested classes (such
    as inner classes), not objects as iv's. Can I assume that an inner class's
    native iv's get a shallow copy as well? I can think of a number of ambiguous
    situations and am wondering if these issues are discussed anywhere, if there
    are any general cautions, etc? Maybe there is nothing to this but on the
    face of it it seems complex.

  • Nested classes inherriting generics?

    I have a comparator decalared in a class, but most of its use will be in a nested class. But i cant figure out how to make the nested class have the same generics as the class its declared in. Some code to help explain my problem.
    import java.util.Comparator;
    public class Test<K, V>
         protected Comparator<? super K> comparator;
         private Node<K,V> root;
         private int size = 0;
         protected final int MINIMUM = 2;
         protected final int MAXIMUM = 2 * this.MINIMUM;
         public Test(Comparator<? super K> comparator)
              this.root = new Node<K, V>();
              this.comparator = comparator;
         @SuppressWarnings({ "hiding", "unchecked" })
         private class Node<K, V>
              Entry<K, V> [] entries = (Entry<K, V>[]) new Object[MAXIMUM];
              @SuppressWarnings("unused")
              Node<K, V> [] links = (Node<K, V>[]) new Object[MAXIMUM + 1];
              public Node(){}
              public void add(K key, V value)
                       int compared = comparator.compare(key, entries[0].key);
              private class Entry<K, V>
                   protected K key;
                   protected V value;
                   public Entry(K key, V value)
                        this.key = key;
                        this.value = value;
    }

    I changed things, but now I am getting a ClassCastException at runtime on the follow lines.
    import java.util.Comparator;
    public class BTree<K, V>
         protected Comparator<? super K> comparator;
         private Node root;
         private int size = 0;
         protected final int MINIMUM = 2;
         protected final int MAXIMUM = 2 * this.MINIMUM;
         public BTree(Comparator<? super K> comparator)
              this.root = new Node();
              this.comparator = comparator;
         public int size()
              return this.size;
         public void add(K key, V value)
              this.root.looseAdd(key, value);
         private class Node
                    //cast cast one these 2 lines
              Entry [] entries = (Entry[]) new Object[MAXIMUM];
              Node [] links = (Node[]) new Object[MAXIMUM + 1];
              public Node(){}
              public void looseAdd(K key, V value)
              private class Entry
                   protected K key;
                   protected V value;
                   public Entry(K key, V value)
                        this.key = key;
                        this.value = value;
    }Edited by: xxpigeonxx on Dec 20, 2009 11:07 PM

  • Nested Class in xpress

    Could someone explain how to instantiate a nested class in xpress? Thanks

    yep sorry about the error there, but it still wont run.
    Through trial and error, ive discoverd that if I comment out the DocumentListener the jar will run fine. This is strange.
    the documentListener now looks like
    DocumentListener listener = new DocumentListener()
          public void changedUpdate(DocumentEvent documentEvent) {
          public void insertUpdate(DocumentEvent documentEvent) {
            if(proceed == true){
                   String temp = textField.getText();
                   System.out.println(temp);
                int tempo = Integer.parseInt(temp);
                   updateBet(tempo);
                   else{
          public void removeUpdate(DocumentEvent documentEvent) {
         };  with this declaration above in the code
    JTextField textField = new JTextField(4);
              final Document document = textField.getDocument();
                    document.addDocumentListener(listener);can anyone see any problems, im tearing my hair out :-<

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Are static nested classes thread-safe?

    There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
    public class SomeMultiThreadedWebController {
    public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
        simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
    protected static class SimpleQueryBuilder {
             private String queryString;
             private Map<String, Object> params = new HashMap<String, Object>();
             public SimpleQueryBuilder(String queryString) {
                  this.queryString = queryString;
             public SimpleQueryBuilder addParameter(String name, Object value) {
                  params.put(name, value);
                  return this;
             public Query createQuery(EntityManager em) {
                  Query query = em.createQuery(queryString);
                  for (Entry<String, Object> entry : params.entrySet()) {
                       query.setParameter(entry.getKey(), entry.getValue());
                  return query;
        public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
             return new SimpleQueryBuilder(queryString);
    }Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

    Hello,
    I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
    Let me correct this (essentially, incorrect uses of the terminology):
    I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
    Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
    I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
    For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
    Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
    Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
    However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
    The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
    Thus any synchronized method(With the limit stated above)
    or immutable member (like primitive type) are thread-safe.
    Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
    a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
    The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
    Additional considerations:
    1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
    2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
    Edited by: jduprez on Mar 4, 2010 9:53 AM

  • How to use multiple classes for each form

    Hi,
    I have created two forms using screen painter and now i want to use different classes for these two forms .
    I have declared the Sbo Connection in main class i.e. Set Application ,Connection Context() but while connecting to other classes
    for executing the code for that form SAP is not connected to that class.How to use multiple classes functionality i don't able to
    do that.Please provide some sample codes for that as it will be more helpful for me to understand.
    Thanks & Regards,
    Amit

    Hi Amit,
    In fact, its more advisable to use separate classes for every form that you use.  Have one common class, say, for eg., clsMain.cs which has all the connection and connectivity to other classes, wherein, the menu event and item event of this main class, will just be calling the menu / item event of other classes.
    The individual functionality of the child classes will be called from the item / menu event of the respective classes.
    Item event in clsMain.cs will be as below.
    private void oApplication_ItemEvent(string FormUID, ref SAPbouiCOM.ItemEvent pVal, out bool BubbleEvent)
                SAPbouiCOM.Form oForm;
                BubbleEvent = true;
                try
                    if ((pVal.FormTypeEx == "My_Form1Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm1_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
                    if ((pVal.FormTypeEx == "My_Form2Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm2_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
    Now, in the individual classes, you can have their respective item events, which will be called from the main class, and the respective functionalities will occur.
    Hope this helps.
    Regards,
    Satish.

  • Static nested class

    Hi there.
    Im playing around with static nested classes:
    class OuterC {
         int x = 10;
         static class Nest {
              void doStuff() {
                   System.out.println("Going");
                   //System.out.println("Should be allowed print: " + x);
                   doOtherStuff();
              public void doOtherStuff() {
                   System.out.println("Doing Stuff!");
    public class Test {
         static class OtherNest {
              void arbitraryMethod() {
                   System.out.println("Going to do arbitrary stuff...");
         public static void main(String[] args) {
              OuterC.Nest n = new OuterC.Nest();
              n.doStuff();
              OtherNest on = new OtherNest();
              on.arbitraryMethod();
    }//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
    I get a "cannot access non-static..." error, which is fine. I expect that.
    But why can I run the doOtherStuff() method from the static nested class Nest?
    doOtherStuff() is after all an instance method...
    Many Thanks & regards!
    Edited by: Boeing-737 on May 29, 2008 10:27 AM
    Dont bother replying, I see the error now. The method is defined as a member within the nested
    class. Apologies, I didn't spot that. My mistake.
    Thanks.
    Edited by: Boeing-737 on May 29, 2008 10:28 AM

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

Maybe you are looking for