Static Class Function vs. Instance Variables

I'm making a Wheel class to spin the wheels on some toy
trains as they move back and forth.
Each wheel on the train is an instance of the Wheel class and
there are several of them.
I thought it would be great to just have a static class
function to tell all the Wheels to start turning:
Wheel.go();
The Wheel class keeps a static array of all of its instances
so I thought I would just loop through all of those instances and
issue the wheelInstance.roll() method.
So far it all works. But I was planning to use a setInterval
to call the roll() method and each instance has its own rollID
property that I would like to assign the setInterval ID to. Here is
the problem.
Since the rollID is an instance property I can't access them
from a static class function. Is there any way to do this?
Currently I"m just using an onEnterFrame which doesn't require me
to use the instance properties.

Technically yes, realistically for this class no.A
class will probably take several hundred bytes at
least to load, with no data of your own. So adding4
bytes for a int is less than 1% of the total size.
And if you are loading millions of differentclasses
then you should rethink your design.If you don't instantiate the class when you reference
a static variable why would you consume memory for the
class other than the variable itself? I don't
understand what you are talking about with the
"millions of different classes", it's not germane to
the question. Bottom line, referencing a static
variable more than once will save memory.Using a class, static or by instance, requires that the class be loaded. A loaded class creates, at the very least, an instance of java.lang.Class. Any static members of the class are in addition to the storage space needed for the instance of java.lang.Class and for any internal storage needed by the JVM in addition to that.
Thus if one has a static data member when the class is used in any way, the static data member takes storage space. However a member (non-static) does not take storage space.
Of course the meta data for the member could take as much space as the static member so the point could be moot. Is that what you were referring to?

Similar Messages

  • Static class functions: PLS-00801: internal error [phd_get_defn:D_S_ED:LHS]

    Any ideas why this would generate an internal error - referring to a static class function in that class constructor's parameter signature?
    Test case (on 11.2.0.2) as follows:
    SQL> create or replace type TMyObject is object(
      2          id      integer,
      3          name    varchar2(30),
      4 
      5          static function DefaultID return integer,
      6          static function DefaultName return varchar2,
      7 
      8          constructor function TMyObject(
      9                  objID integer default TMyObject.DefaultID(), objName varchar2 default TMyObject.DefaultName()
    10          )return self as result
    11  );
    12  /
    Type created.
    SQL>
    SQL> create or replace type body TMyObject is
      2 
      3          static function DefaultID return integer is
      4          begin
      5                  return( 0 );
      6          end;
      7 
      8          static function DefaultName return varchar2 is
      9          begin
    10                  return( 'foo' );
    11          end;
    12 
    13          constructor function TMyObject(
    14                  objID integer default TMyObject.DefaultID(), objName varchar2 default TMyObject.DefaultName()
    15          )return self as result is
    16          begin
    17                  self.id := objId;
    18                  self.name := objName;
    19                  return;
    20          end;
    21 
    22  end;
    23  /
    Type body created.
    SQL>
    SQL> declare
      2          obj     TMyObject;
      3  begin
      4          obj := new TMyObject();
      5  end;
      6  /
    declare
    ERROR at line 1:
    ORA-06550: line 0, column 0:
    PLS-00801: internal error [phd_get_defn:D_S_ED:LHS]If the static class functions are removed from the constructor and applied instead inside the constructor body, it works without error. Likewise you can call the constructor with the static class functions as parameters, without an internal error resulting.
    SQL> create or replace type TMyObject is object(
      2          id      integer,
      3          name    varchar2(30),
      4 
      5          static function DefaultID return integer,
      6          static function DefaultName return varchar2,
      7 
      8          constructor function TMyObject(
      9                  objID integer default null, objName varchar2 default null
    10          )return self as result
    11  );
    12  /
    Type created.
    SQL>
    SQL> create or replace type body TMyObject is
      2 
      3          static function DefaultID return integer is
      4          begin
      5                  return( 0 );
      6          end;
      7 
      8          static function DefaultName return varchar2 is
      9          begin
    10                  return( 'foo' );
    11          end;
    12 
    13          constructor function TMyObject(
    14                  objID integer default null, objName varchar2 default null
    15          )return self as result is
    16          begin
    17                  self.id := nvl( objId, TMyObject.DefaultID() );
    18                  self.name := nvl( objName, TMyObject.DefaultName() );
    19                  return;
    20          end;
    21 
    22  end;
    23  /
    Type body created.
    SQL>
    SQL> declare
      2          obj     TMyObject;
      3  begin
      4          obj := new TMyObject();
      5  end;
      6  /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> declare
      2          obj     TMyObject;
      3  begin
      4          obj := new TMyObject(
      5                          objID => TMyObject.DefaultID(),
      6                          objName => TMyObject.DefaultName()
      7                  );
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    SQL> Had a quick look on support.oracle.com and did not turn up any specific notes dealing with the use of static class functions in the parameter signature of the constructor. Known issue? Any other workaround besides the one above?

    Hi,
    there is a bug: "Bug 8470406: OBJECT INSTANCE CREATION FAILS WITH ERROR PLS-00801 IN 11GR1", it shows the behaviour in 11g but not in 10.2. It gives exactly the symptoms you also see, move it to the body and it works. But there is no solution/patch given.
    Herald ten Dam
    http://htendam.wordpress.com

  • Static Classes/Methods vs Objects/Instance Classes/Methods?

    Hi,
    I am reading "Official ABAP Programming Guidelines" book. And I saw the rule:
    Rule 5.3: Do Not Use Static Classes
    Preferably use objects instead of static classes. If you don't want to have a multiple instantiation, you can use singletons.
    I needed to create a global class and some methods under that. And there is no any object-oriented design idea exists. Instead of creating a function group/modules, I have decided to create a global class (even is a abstract class) and some static methods.So I directly use these static methods by using zcl_class=>method().
    But the rule above says "Don't use static classes/methods, always use instance methods if even there is no object-oriented design".
    The book listed several reasons, one for example
    1-) Static classes are implicitly loaded first time they are used, and the corresponding static constructor -of available- is executed. They remain in the memory as long as the current internal session exists. Therefore, if you use static classes, you cannot actually control the time of initialization and have no option to release the memory.
    So if I use a static class/method in a subroutine, it will be loaded into memory and it will stay in the memory till I close the program.
    But if I use instance class/method, I can CREATE OBJECT lo_object TYPE REF TO zcl_class then use method lo_object->method(), then I can FREE  lo_object to delete from the memory. Is my understanding correct?
    Any idea? What do you prefer Static Class OR Object/Instance Class?
    Thanks in advance.
    Tuncay

    @Naimesh Patel
    So you recommend to use instance class/methods even though method logic is just self-executable. Right?
    <h3>Example:</h3>
    <h4>Instance option</h4>
    CLASS zcl_class DEFINITION.
      METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    <h4>Static option</h4>
    CLASS zcl_class DEFINITION.
      CLASS-METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      CLASS-METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
    zcl_class=>add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
    zcl_class=>subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    So which option is best? Pros and Cons?

  • Instance variable to hold the element of a tag in the xml file

    Hi I have an xml file that is handled using this parser
    <attr id="MY_NAME" >
    this parser hanled the above tag but now I want to have it handle
    <attr id="MY_NAME" desc="GOOD">
    but I need to create an instance variable to handle the desc element in the attr tag .
    Can some one help me out as this is not my file and I am having trouble to do please......
    import java.util.*;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
       The SupportMatrix class provides static variables and methods to simplify
       the determination of whether or not a given attribute is supported for a
       certain object type (queue manager, channel, etc.), depending on the version
       and platform of the queue manager to which it belongs.
       The SupportMatrix class may not be instantiated. Its constructor is private.
       An instance of the class is created internally in the static initializer so
       that the XML parsing methods are available.
       A corresponding XML document, SupportMatrix.xml, is parsed to create the various
       HashMaps which contain the version/platform dependency information. A number of
       inner classes are used to represent the various elements of the XML matrix
       definition.
       Here's a sample document:
       <!-- The supportmatrix tag opens the document -->
       <supportmatrix>
         <!-- Objects are keyed by classid. "1" is the classid of a queue manager object. -->
         <object classid="1">
           <!-- Versions group attributes according to the queue manager version where they
                were introduced. The "base" cmdlevel encompasses all versions up to 5.1. -->
           <version cmdlevel="base">
             <!-- Attributes are defined by the attr tag. -->
             <attr id="MQCA_Q_MGR_NAME">
               <!-- Support elements define the platform-specific requirements for an attribute. -->
               <support platforms="UNIX,WINDOWS,OS400,VMS,NSK" maxlen="48" type="MQCFST"/>
               <support platforms="MVS" maxlen="4" type="MQCFST"/>
             </attr>
             <attr id="MQCA_Q_MGR_DESC">
               <!-- Specific attribute characteristics, most notably maximum len for string parms,
                    are defined in the support element. As shown in the following example, it may
                    apply to all platforms. -->
               <support platforms="all" maxlen="64" type="MQCFST"/>
             </attr>
             <!-- Support elements are optional. -->
             <attr id="MQIA_PLATFORM"/>
             <attr id="MQIA_COMMAND_LEVEL"/>
           </version>
           <!-- The version element may 'include' other versions. Note that object elements
                may also refer to other objects via the 'include' parm of the object tag.
                This is to allow common attributes (especially for queues and channels) to
                be shared by multiple definitions in order to reduce some of the
                redundancy. -->
           <version cmdlevel="520" include="base">
           </version>
         </object>
       </supportmatrix>
       The inner classes, and their hierarchical relationships are as follows:
         SupportObject - corresponds to the <object> element. Stored in a static HashMap, and
                         keyed by classid.
           VersionObject - corresponds to the <version> element. Stored in a HashMap instance
                           variable of the SupportObject class, keyed by cmdlevel.
             AttributeObject - corresponds to the <attr> element. Stored in a HashMap instance
                               variable of the VersionObject class, keyed by attribute name.
               PlatformObject - corresponds to the <support> element. Stored in HashMaps belonging
                                to the AttributeObjects, keyed by platform. A single PlatformObject
                                instance is created when the support tag is encountered. The
                                "platforms" attribute of the support element is then processed. For
                                each platform in the comma-delimited list, an entry is added to the
                                collection of PlatformObjects. This is to greatly simplify later
                                lookups.
       In order to support the 'include' feature of object and version elements, certain
       functions are recursive. If the attribute to be validated is not found for the passed
       cmdlevel, the 'parent' VersionObject is consulted by means of the 'include' value. If
       the chain of VersionObjects has been exhausted and the attribute in question has still not
       been located, the next SupportObject in the chain is consulted in a similar fashion.
    public class SupportMatrix extends DefaultHandler {
        /** The objects collection holds all the SupportObjects, keyed by classid. */
        private static HashMap objects;
        /** xmlFile will name the xml document to be parsed. Note that using the
            default class loader expects the string to be the path to the file. It must
            NOT begin with the '/' character. */
        private static String xmlFile =
            ResourceManager.getApplicationProperties().getProperty("SupportMatrixFile");
        private Stack stack;
        /** This static initializer allocates the static objects collection, creates an
            instance of the SupportMatrix class for xml parsing purposes, and initiates
            the parse operation to populate the collection. */
        static {
            objects = new HashMap();
            // Create a parser and process the xml doc
            SupportMatrix handler = new SupportMatrix();
            InputSource is = null;
            try {
                is = new InputSource(ClassLoader.getSystemClassLoader().getResourceAsStream(xmlFile));
                XMLReader xmlReader =
                    SAXParserFactory.newInstance().newSAXParser().getXMLReader();
                xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
                xmlReader.setContentHandler(handler);
                if (is == null) {
                    System.err.println("No input stream, dammit");
                xmlReader.parse(is);
            } catch(Exception e) {
                e.printStackTrace();
        /** Private constuctor, used only for XML parsing. */
        private SupportMatrix() {
            stack = new Stack();
        /** Add a SupportObject instance to the objects collection. */
        private void addObject(SupportObject obj) {
            String key = obj.getClassId();
            objects.put(key, obj);
        /* DefaultHandler methods                                              */
        /** Not used. */
        public void characters(char[] ch, int start, int length) {}
        /** Not used. */
        public void endDocument() {}
        /** For the version, object, and attr elements, pop the top element of the stack. */
        public void endElement(String uri, String localName, String qName) {
            if (localName.equals("version") || localName.equals("object") || localName.equals("attr")) {
                stack.pop();
        /** Not used. */
        public void setDocumentLocator(Locator locator) {}
        /** Not used. */
        public void startDocument() {}
        /** Most of the work is done here. Create the appropriate inner class instance for
            element; for object, version, and attr, push the element onto the stack so that
            child elements may be added to their collections as needed. */
        public void startElement(String uri, String localName, String qName,
                                 Attributes attributes) {
            String include = attributes.getValue("include");
            if (localName.equals("object")) {
                SupportObject obj = new SupportObject(attributes.getValue("classid"), include);
                addObject(obj);
                stack.push(obj);
            } else if ( localName.equals("version")) {
                VersionObject ver = new VersionObject(attributes.getValue("cmdlevel"), include);
                ((SupportObject)stack.peek()).addVersion(ver);
                stack.push(ver);
            } else if ( localName.equals("attr")) {
                AttributeObject a = new AttributeObject(attributes.getValue("id"));
                //String desc = StringFactory.getString(attributes.getValue("desc"));
                //if(desc != null)
                   //     a.setAttribute();
                String readonly = attributes.getValue("readonly");
                String exclude = attributes.getValue("exclude");
                if (include != null && exclude != null) {
                    Log.log(Log.ERROR, this, "include and exclude are mutually exclusive, exclude value ignored");
                    exclude = null;
                if (include != null) {
                    a.setCondition(include, true);
                if (exclude != null) {
                    a.setCondition(exclude, false);
                if (readonly != null)
                    a.setReadonly(readonly.equals("y"));
                ((VersionObject)stack.peek()).addAttr(a);
                stack.push(a);
            } else if (localName.equals("support")) {
                String platforms = attributes.getValue("platforms");
                String readonly = attributes.getValue("readonly");
                String maxlen = attributes.getValue("maxlen");
                String type = attributes.getValue("type");
                int attrType = 0;
                if (type != null) {
                    if (type.equals("MQCFIN")) {
                        attrType = CMQCFC.MQCFT_INTEGER;
                    } else if (type.equals("MQCFIL")) {
                        attrType = CMQCFC.MQCFT_INTEGER_LIST;
                    } else if (type.equals("MQCFST")) {
                        attrType = CMQCFC.MQCFT_STRING;
                    } else if (type.equals("MQCFSL")) {
                        attrType = CMQCFC.MQCFT_STRING_LIST;
                    } else if (type.equals("EXBIN")) {
                        attrType = MqcConstants.EXCFT_BINARY;
                    } else if (type.equals("EXPCF")) {
                        attrType = MqcConstants.EXCFT_PCF;
                PlatformObject p = null;
                if (readonly == null) {
                    p = new PlatformObject(platforms);
                } else {
                    p = new PlatformObject(platforms, readonly.equals("y"));
                String exclude = attributes.getValue("exclude");
                if (include != null && exclude != null) {
                    Log.log(Log.ERROR, this, "include and exclude are mutually exclusive, exclude value ignored");
                    exclude = null;
                if (include != null)
                    p.setCondition(include, true);
                if (exclude != null)
                    p.setCondition(exclude, false);
                if (attrType != 0)
                    p.setType(attrType);
                if (maxlen != null)
                    p.setLen(Integer.parseInt(maxlen));
                ((AttributeObject)stack.peek()).addPlatform(p);
        public static boolean isExported(int attribute, TopologyModelNode node) {
            String name = ResourceManager.getAttributeName(attribute);
            return isExported(name, node);
        public static boolean isExported(String attribute, TopologyModelNode node) {
            // Find the qmgr node to fetch platform and cmdlevel
            TopologyModelNode qmgr = node.getModel().getQMgrNode(node.getAddress());
            // If there's no qmgr for this node, it must be one of 'ours'.
            if (qmgr == null)
                return false;     // None of 'our' objects can be exported to MQSC.
            String classId = node.getClassId();
            String cmdLevel = qmgr.getAttributeValue("MQIA_COMMAND_LEVEL");
            String platform = qmgr.getAttributeValue("MQIA_PLATFORM");
            return isExported(attribute, classId, cmdLevel, platform, node);
        public static boolean isExported(int attribute, String classId, String cmdLevel, String platform,
                                         TopologyModelNode node) {
            String name = ResourceManager.getAttributeName(attribute);
            return isExported(name, classId, cmdLevel, platform, node);
        /** Determine if an attribute is exportable. The attribute name, the classid of the object to
            which it belongs, plus the command level and platform of the queue manager are all needed
            to make this determination.
            Start by finding the AttributeObject for the combination of attribute, classid, and
            command level. If we can't find the AttributeObject, we assume that the attribute
            is not exported. Otherwise, find out if it is exportable for the selected platform.
        public static boolean isExported(String attribute, String classId, String cmdLevel, String platform,
                                         TopologyModelNode node) {
            AttributeObject attr = getAttributeObject(attribute, classId, cmdLevel);
            if (attr == null) {
                return false;
            } else {
                return attr.isExported(platform, node);
        public static boolean isSupported(int attribute, TopologyModelNode node) {
            String name = ResourceManager.getAttributeName(attribute);
            return isSupported(name, node);
        public static boolean isSupported(String attribute, TopologyModelNode node) {
            // Find the qmgr node to fetch platform and cmdlevel
            TopologyModelNode qmgr = node.getModel().getQMgrNode(node.getAddress());
            // If there's no qmgr for this node, it must be one of 'ours'.
            if (qmgr == null)
                return true;
            String classId = node.getClassId();
            String cmdLevel = qmgr.getAttributeValue("MQIA_COMMAND_LEVEL");
            String platform = qmgr.getAttributeValue("MQIA_PLATFORM");
            return isSupported(attribute, classId, cmdLevel, platform);
        public static boolean isSupported(int attribute, String classId, String cmdLevel, String platform) {
            String name = ResourceManager.getAttributeName(attribute);
            return isSupported(name, classId, cmdLevel, platform);
        /** Determine if an attribute is supported. The attribute name, the classid of the object to
            which it belongs, plus the command level and platform of the queue manager are all needed
            to make this determination.
            Start by finding the SupportObject for the classid. If it isn't there, we make the assumption
            (for now) that the attribute is supported. The only classids for which this can occur are
            broker, agent, and the various container objects.
            Propagate the isSupported request to the chain of SupportObjects (based on 'include' values)
            until we get a 'true' result or we run out of SupportObjects. */
        public static boolean isSupported(String attribute, String classId, String cmdLevel, String platform) {
            if (attribute == null)
                return false;
            SupportObject obj = (SupportObject)objects.get(classId);
            // If the object type isn't even in the support matrix, we interpret that to
            // mean that it's a Broker or Agent, in which case all attributes are supported
            // at present.
            if (obj == null)
                return true;
            boolean result = false;
            while (result == false && obj != null) {
                result = obj.isSupported(attribute, cmdLevel, platform);
                if (result == false && obj.getInclude() != null) {
                    obj = (SupportObject)objects.get(obj.getInclude());
                } else
                    obj = null;
            return result;
        /** Locate an AttributeObject for a given attribute name, object type, and command level.
            This is a helper function for the getMaxLen and getType methods. */
        private static AttributeObject getAttributeObject(String attr, String classID, String cmdLevel) {
            AttributeObject result = null;
            SupportObject obj = (SupportObject)objects.get(classID);
            while (result == null && obj != null) {
                result = obj.getAttr(attr, cmdLevel);
                if (result == null && obj.getInclude() != null) {
                    obj = (SupportObject)objects.get(obj.getInclude());
                } else
                    obj = null;
            return result;
        /** Determine the maximum length for a given combintation of attribute name, object type,
            command level, and platform. If the AttributeObject can't be found, or if the length
            hasn't been set, return -1. */
        public static int getMaxLen(String attr, String classId, String cmdLevel, String platform) {
            AttributeObject a = getAttributeObject(attr, classId, cmdLevel);
            if (a == null)
                return -1;
            return a.getMaxLen(platform);
        /** Determine the PCF parm type for a given combintation of attribute name, object type,
            command level, and platform. If the AttributeObject can't be found, or if the length
            hasn't been set, return -1. */
        public static int getType(String attr, String classId, String cmdLevel, String platform) {
            AttributeObject a = getAttributeObject(attr, classId, cmdLevel);
            if (a == null)
                return -1;
            return a.getType(platform);
        /** Inner class to contain platform-specific info for an attribute. */
        class PlatformObject {
            /** This instance variable will contain the comma-delimited string of all
                platforms to which this object applies. */
            private String platform;
            private int maxlen;
            private String condition = null;
            private boolean include;
            private boolean readonly;
            private boolean lenSet;
            private int attrType;
            private boolean typeSet;
            public PlatformObject(String p, boolean readonly) {
                platform = p;
                this.readonly = readonly;
                lenSet = false;
                typeSet = false;
            public PlatformObject(String p) {
                this(p, false);
            public void setCondition(String condition, boolean include) {
                this.condition = condition;
                this.include = include;
            public boolean isReadonly() {
                return readonly;
            public boolean isExported(TopologyModelNode node) {
                if (condition != null) {
                    boolean test = false;
                    try {
                        test = Utilities.evaluateCondition(node, condition);
                    } catch (Exception e) {}
                    if (include ^ test)
                        return false;
                return !readonly;
            public void setLen(int len) {
                maxlen = len;
                lenSet = true;
            public void setType(int type) {
                attrType = type;
                typeSet = true;
            public String getPlatform() {
                return platform;
            public int getMaxLen() {
                if (!lenSet)
                    return -1;
                return maxlen;
            public int getType() {
                if (!typeSet)
                    return -1;
                return attrType;
        /** This class represents a specific MQSeries attribute. It can optionally contain
            instances of the PlatformObject class as needed. When the 'platforms' collection
            is empty, the attribute is supported on all platforms. It is also possible to
            include a PlatformObject for the 'all' platform, if specific attribute characteristics
            need representation. When the 'platforms' collection is non-empty, it will include one
            entry for each platform where the attribute is supported. */
        class AttributeObject {
            private String attribute;
            private String attrValue;
            private HashMap platforms;
            private String condition = null;
            private boolean include;
            private boolean readonly = false;
            public AttributeObject(String a) {
                this(a, false);
            public AttributeObject(String a, boolean readonly) {
                attribute = a;
                platforms = new HashMap();
                this.readonly = readonly;
            public void setCondition(String condition, boolean include) {
                this.condition = condition;
                this.include = include;
            public void setReadonly(boolean readonly) {
                this.readonly = readonly;
            public boolean isReadonly() {
                return readonly;
            public void addPlatform(PlatformObject p) {
                for (StringTokenizer st = new StringTokenizer(p.getPlatform(), ","); st.hasMoreTokens() ;) {
                    platforms.put(st.nextToken(), p);
            public PlatformObject getPlatform(String platform) {
                PlatformObject p = (PlatformObject)platforms.get(platform);
                if (p == null)
                    p = (PlatformObject)platforms.get("all");
                return p;
            public String getAttribute() {
                return attribute;
            public int getMaxLen(String platform) {
                PlatformObject p = getPlatform(platform);
                if (p == null)
                    return -1;
                return p.getMaxLen();
            public int getType(String platform) {
                PlatformObject p = getPlatform(platform);
                if (p == null)
                    return -1;
                return p.getType();
            public boolean isSupported(String platform) {
                if (platforms.isEmpty()) {
                    return true;
                if (platforms.containsKey(platform)) {
                    return true;
                if (platforms.containsKey("all")) {
                    return true;
                return false;
            public boolean isExported(String platform, TopologyModelNode node) {
                if (readonly) {
                    Log.log(Log.DEBUG, this, attribute + " is readonly, returning false");
                    return false;
                if (condition != null) {
                    Log.log(Log.DEBUG, this, "Testing condition = " + condition);
                    boolean test = false;
                    try {
                        test = Utilities.evaluateCondition(node, condition);
                        Log.log(Log.DEBUG, this, "Condition result is " + test);
                    } catch (Exception e) {
                        Log.log(Log.ERROR, this, "Condition through an exception");
                    if (include ^ test)
                        return false;
                if (platforms.isEmpty()) {
                    return true;
                PlatformObject p = getPlatform(platform);
                if (p == null) {
                    Log.log(Log.DEBUG, this, platform + " not found for " + attribute + ", returning false");
                    return false;
                return p.isExported(node);
        /** This class represents a specific value of a queue manager's command level. A
            given instance of this class may 'include' a 'parent' instance through its
            include instance variable. The traversal of the parent/child hierarchy is
            delegated to the SupportObject class, since that is where the collection of
            VersionObjects lives. */
        class VersionObject {
            private String cmdLevel;
            private String include;
            private HashMap attributes;
            public VersionObject(String cmdLevel, String include) {
                this.cmdLevel = cmdLevel;
                this.include = include;
                attributes = new HashMap();
            public void addAttr(AttributeObject attr) {
                attributes.put(attr.getAttribute(), attr);
            public AttributeObject getAttr(String attr) {
                return (AttributeObject)attributes.get(attr);
            public String getCmdLevel() {
                return cmdLevel;
            public String getInclude() {
                return include;
            public boolean isSupported(String attr, String platform) {
                AttributeObject obj = (AttributeObject)attributes.get(attr);
                if (obj == null) {
                    return false;
                } else
                    return obj.isSupported(platform);
        /** This class represents an MQSeries object type, as identified by its classid, e.g.
            queue manager or local queue. This class implements an include facility similar to
            that described for the VersionObject. The traversal of that hierarchy is delegated
            to the static isSupported method, because the collection of SupportObject instances
            is a static variable of the SupportMatrix class. */
        class SupportObject {
            private String classId;
            private String include;
            private HashMap versions;
            public SupportObject(String classId, String include) {
                this.classId = classId;
                this.include = include;
                versions = new HashMap();
            public void addVersion(VersionObject obj) {
                String key = obj.getCmdLevel();
                versions.put(key, obj);
            public String getClassId() {
                return classId;
            public String getInclude() {
                return include;
            public boolean isSupported(String attr, String cmdLevel, String platform) {
                boolean result = false;
                VersionObject obj = (VersionObject)versions.get(cmdLevel);
                if (obj == null)
                    obj = (VersionObject)versions.get("base");
                // I don't actually know what it means if obj is null at this point.
                // It probably can't happen.
                if (obj == null)
                    return false;
                while (result ==  false && obj != null) {
                    result = obj.isSupported(attr, platform);
                    if (result == false && obj.getInclude() != null) {
                        obj = (VersionObject)versions.get(obj.getInclude());
                    } else
                        obj = null;
                return result;
            public AttributeObject getAttr(String attr, String cmdLevel) {
                AttributeObject result = null;
                VersionObject obj = (VersionObject)versions.get(cmdLevel);
                if (obj == null)
                    obj = (VersionObject)versions.get("base");
                // I don't actually know what it means if obj is null at this point.
                // It probably can't happen.
                if (obj == null)
                    return null;
                while (result ==  null && obj != null) {
                    result = obj.getAttr(attr);
                    if (result == null && obj.getInclude() != null)
                        obj = (VersionObject)versions.get(obj.getInclude());
                    else
                        obj = null;
                return result;
    }

    Are you the one who commented out the code you're looking for ?//String desc = StringFactory.getString(attributes.getValue("desc"));You just have to modify you AttributeObject class to hold a new field : String description. And then, it's up to you to create a new constructor or a new setter method.
    Btw, this is not a Swing related question.

  • Scope of 'static classes'

    Hello,
    I would like to implement a LogWriter and avoid to create an object during application start and pass the LogWriter object to all classes writing logs. So the idea is simply to initialize some parameters (like logfile name) during application start and provide the LogWriter methods like writeLog as static methods. This works fine in a single user environment.
    Question: What is the scope of the 'static' class. For instance if I set the Logfile according to a user name in the servlet init method, is this system wide or runs it in the context of the user?
    Regards, rainer

    Hello,
    two answers. I did not use log4j for two reasons
    1) I'm quite new to java and didn't know this project
    2) Sometimes it's easier to provide some own code than convincing the customer to install and maintain an additional package. I do not want to maintain any software installations of additional packages for my tiny project if the time saving is not essential. In this case it took me less than one day to write my own logger class which provides enough functions for my need (e.g. level based filtering, formatted output, ...).
    Back to the initil question bout lifetime. If a servlet is initilaized only once for many sessions and if I create any (static) helper object during Servlet init then this helper object is the same for all sessions and not only for all Get/Post's of this single session. That's what I needed to know.
    Regards, Rainer

  • When can I make instance variables public?

    I noticed that some of the in-built Java classes have public instance variables, for example in Rectangle the variables x, y, width and height are all directly accessible from outside. When is it okay to make public instance variables? Is it when they are primitive types? I thought maybe it is when they are final variables - but that can't be the case because you can directly modify the Rectangle's public instance variables.
    I've always used getter and setter methods in my objects because I was told "making instance variables public is bad". But obviously this isn't necessarily the case (unless the guys at Java are bad programmers). I think directly accessing the instance variables makes for much neater and more readable code. Is there any convention or best-practise guidelines on when I can or can not make them public?
    P.S. I also just "don't get" why you can't make them public if you're just going to provide a getter and setter method anyway... what's the difference? I suppose the theory is that the setter method should do some checking to make sure the input is valid. But what if the setter method just accepts -anything- of the appropriate type (accepts any Rectangle, for example)? What's the use of hiding the instance variables?
    teach me.
    Thanks. ;-)

    For the most part, it is true that making instance member variables other than private is not a good idea. This concept, known in OO circles as "information hiding", typically allows the greatest flexibility in internal implementation of a class, since you can change the internal structure of the class without affecting the clients that use the class.
    Let me add that Sun's programmers are a team, and teams have members of differing capabilities.
    It is also true that there may be cases where exposing instance variables is unlikely to cause problems. Simple classes, or very stable classes that will not change are some examples, but not all.
    Following a guideline blindly is not a good idea either. You need to evaluate each instance in which you decide you might want to deviate from "good programming practices". Still, best practices are best practices for a reason. It is best to understand them, and then decide if you can violate them.
    For my own part, I don't think it is "neater" to expose such variables, and I have personally had to deal with situations where a change in a class's internal structure was extremely painful because the original developer chose to make all his instance variables public.
    {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Convertion of class variable (static) into instance variable(non-static)!

    Dear all,
    got a slight different question.
    Is that possible to convert class variable (static) into instance variable(non-static)?
    If so, how to make the conversion?
    Appreciating your replies :)
    Take care all,
    Leslie V
    http://www.googlestepper.blogspot.com
    http://www.scrollnroll.blogspot.com

    JavaDriver wrote:
    Anything TBD w.r.to pass by value/reference (without removing 'static' keyword)?Besides the use of acronyms in ways that don't make much sense there are two other large problems with this "sentence".
    1) Java NEVER passes by reference. ALWAYS pass by value.
    2) How parameters are passed has exactly zero to do with static.
    Which all means you have a fundamentally broken understanding of how Java works at all.
    Am I asking something apart from this?
    Thanks for your reply!
    Leslie VWhat you're asking is where to find the tutorials because you're lost. Okay. Here you go [http://java.sun.com/docs/books/tutorial/java/index.html]
    And also for the love of god read this [http://www.javaranch.com/campfire/StoryPassBy.jsp] There is NO excuse for not knowing pass-by in Java in this day and age other than sheer laziness.

  • Binding a JavaFX variable to a Java class instance variable

    Hi,
    I am pretty new to JavaFX but have been developing in Java for many years. I am trying to develop a JavaFX webservice client. What I am doing is creating a basic scene that displays the data values that I am polling with a Java class that extends Thread. The Java class is reading temperature and voltage from a remote server and storing the response in an instance variable. I would like to bind a JavaFx variable to the Java class instance variable so that I can display the values whenever they change.
    var conn: WebserviceConnection; // Java class that extends Thread
    var response: WebserviceResponse;
    try {
    conn = new WebserviceConnection("some_url");
    conn.start();
    Thread.sleep(10000);
    } catch (e:Exception) {
    e.printStackTrace();
    def bindTemp = bind conn.getResponse().getTemperature();
    def bindVolt = bind conn.getResponse().getVoltage();
    The WebserviceConnection class is opening a socket connection and reading some data in a separate thread. A regular socket connection is used because the server is not using HTTP.
    When I run the application, the bindTemp and bindVolt are not updated whenever new data values are received.
    Am I missing something with how bind works? Can I do what I want to do with 'bind'. I basically want to run a separate thread to retrieve data and want my UI to be updated when the data changes.
    Is there a better way to do this than the way I am trying to do it?
    Thanks for any help in advance.
    -Richard

    Hi,
    If you don't want to constantly poll for value change, you can use the observer design pattern, but you need to modify the classes that serve the values to javafx.
    Heres a simple example:
    The Thread which updates a value in every second:
    // TimeServer.java
    public class TimeServer extends Thread {
        private boolean interrupted = false;
        public ValueObject valueObject = new ValueObject();
        @Override
        public void run() {
            while (!interrupted) {
                try {
                    valueObject.setValue(Long.toString(System.currentTimeMillis()));
                    sleep(1000);
                } catch (InterruptedException ex) {
                    interrupted = true;
    }The ValueObject class which contains the values we want to bind in javafx:
    // ValueObject.java
    import java.util.Observable;
    public class ValueObject extends Observable {
        private String value;
        public String getValue() {
            return this.value;
        public void setValue(String value) {
            this.value = value;
            fireNotify();
        private void fireNotify() {
            setChanged();
            notifyObservers();
    }We also need an adapter class in JFX so we can use bind:
    // ValueObjectAdapter.fx
    import java.util.Observer;
    import java.util.Observable;
    public class ValueObjectAdapter extends Observer {
        public-read var value : String;
        public var valueObject : ValueObject
            on replace { valueObject.addObserver(this)}
        override function update(observable: Observable, arg: Object) {
             // We need to run every code in the JFX EDT
             // do not change if the update method can be called outside the Event Dispatch Thread!
             FX.deferAction(
                 function(): Void {
                    value = valueObject.getValue();
    }And finally the main JFX code which displays the canging value:
    // Main.fx
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.text.Text;
    import javafx.scene.text.Font;
    import threadbindfx.TimeServer;
    var timeServer : TimeServer;
    var valueObjectAdapter : ValueObjectAdapter = new ValueObjectAdapter();
    timeServer = new TimeServer();
    valueObjectAdapter.valueObject = timeServer.valueObject;
    timeServer.start();
    Stage {
        title: "Time Application"
        width: 250
        height: 80
        scene: Scene {
            content: Text {
                font : Font {
                    size : 24
                x : 10, y : 30
                content: bind valueObjectAdapter.value;
    }This approach uses less cpu time than constant polling, and changes aren't dependent on the polling interval.
    However this cannot be applied to code which you cannot change obviously.
    I hope this helps.

  • JDEVELOPER 10G, ADF BC: Passivate static instance variables in AM?

    I understand the need to passivate/activate instance variables but what about static instance variables within an application module?
    Thanks,
    Wes

    Static variables - being class variables and not instance variables - persist without a need for passivation. Is there a particular reason or scenario why to use static variables? You have to consider that since all AM instances will share it, changing it in one AM instance - i.e. one user session - will affect all other AM instances - i.e. all other user sessions! You also have to consider the implications of multithreading when attempting to modify the static variable.

  • Stateless Bean - scope of instance variable in EJB Timer call back function

    Hi,
    I would like to know on the scope of an instance variable of a Stateless Bean object,
    when used in a EJB Timer call back.Let me explain this in more detail below.
    I have a requirement to use a EJB Timer.
    For this, I have created a stateless object since Timer creation needs to be done
    from a stateless bean. I have a member variable "count" of the stateless bean class.
    In the timer call back(ejbTimeout), I am able to use this count variable during
    each time of the call back, and the value of this variable is also updated properly.
    I have a few queries with respect to the above behaviour:
    1) Does stateless bean object not get destroyed once the Timer is created from the Bean?
    2) If the Bean object is not destroyed, then when does the bean object get destroyed?
    3) If both (1) and (2) are not true, then can anyone explain on how the above behaviour is possible?
    Thanks in advance,
    Ulrich

    Hi Ulrich,
    The ejb timer is associated with the stateless session bean component, not with a particular bean instance. There is no formal relationship between the bean instance that called createTimer() and the bean instance on which the timer callback happens. If they're the same in your test run that's just a coincidence and not something your application should be depending on.
    In the stateless session bean model, the container can create and destroy stateless session bean instances at any time. The container is free to pick any stateless session bean instance to service any client invocation or timer callback. If you need to pass context into a timer callback, one way to do it is via the timer "info" object. However, the info object is immutable so it wouldn't be a good match for a counter. You could of course always just use a database for any necessary coordinated state.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Loading Variables in a Class Function

    I am having problems loading variables from an external text
    file inside of a class function. The text file has been created
    properly, and the code that I use in the class is as follows:
    _root.createEmptyMovieClip("texRules", -100);
    loadVariables("texRules.txt", _root.texRules);
    m_Rules = _root.texRules.rules;
    I create an empty movie clip on the root frame named
    texRules, load the variables into that movie clip with the next
    line and then set my member string value equal to the text file
    variable named rules. When I run the program, I get an undefined
    for my m_Rules.
    Here is my texRules.txt:
    rules=THESE ARE THE TEXAS HOLD'EM RULES.
    Any ideas as to what I am doing incorrectly?

    I've opted to use the LoadVars instead of creating an empty
    movie clip and loading the variables there. Here is my new code.
    public function setRules():Void
    var rulesLoader:LoadVars = new LoadVars();
    rulesLoader.onLoad = function (success:Boolean):Void
    if (success)
    trace(rulesLoader.rules);
    this.m_Rules = rulesLoader.rules;
    else
    trace( "Unable to load external file.");
    rulesLoader.load("texRules.txt");
    Here is where I define my properties of my class:
    class TexHoldem extends Game
    //Class member properties
    //Private Properties
    private var m_Rules:String;
    private var m_Target:MovieClip;
    Here is my constructor:
    public function TexHoldem(target)
    this.m_Target = target;
    super("Texas No Limit Hold'Em", 0, 1);
    setRules();
    The setRules function works fine, the only problem now is
    that I can't save the variables once the onLoad function goes out
    of scope. I've thought of modifying it so that it returns a type,
    but that seems difficult. The two easiest solutions I see is to
    create an empty text field that holds the string or find a way to
    get the rulesLoader.rules outside of the onLoad scope. Any
    suggestions now? Sorry to change the problem on you.

  • Static class variable

    Folks:
    I am little confused by static class variables in Java. Since Java doesn't have global varaibles it uses static variables instead. Please take a look at the following code and please tell me what goes wrong.
    /********** CONTENT OF Stack.java ***********/
    import java.util.Stack;
    public class StackClass
    {   static  Stack stack = new Stack (); }
    /********** CONTENT OF Test1 .java ***********/
    public class Test1
    public static void main( String[] args )
    StackClass.stack.push("Hello World");
    /********** CONTENT OF Test2.java ***********/
    public class Test2
    public static void main( String[] args )
    System.out.println( "Top on stack is " + StackClass.stack.peek() );
    I execute the above programs in the sequence of StackClass.java, Test1.java and Test2.java. I think in Test1.java after I push one element to the stack it should still be in the stack in Test2.java But I got :
    java.util.EmptyStackException
         at java.util.Stack.peek(Unknown Source)
         at Test2.main(Test2.java:16)
    Exception in thread "main"
    Can anybody give me a hint?
    Thanks a lot !

    After you run StackClass, the JVM (java.exe) ends and all the classes are unloaded including StackClass
    When you run Test1, StackClass is loaded, an item is pushed on the stack, and then the JVM exits and all classes are unloaded including StackClass
    When you run Test2, StackClass is loaded, and you get an error because the StackClass which was just loaded has no items in it.

  • Singleton instance vs static class

    Hi,
    I often got confused to identify when is better to use a singleton instance and when is better use a static class insted.
    Could someone please advise what criteria should be observed to decide which way is better?
    Thanks in advance,

    A class with all static methods generally connotes a helper class that supplies behavior or enforces business rules of other objects. A class with only state and no behavior is typically encountered in distributed systems, also known as a transfer object. Most true objects have both state and behavior. A singleton is simply a normal object that ensures only a single instance of itself will ever be created and returned for use to a caller.
    - Saish

  • I want to access that BEA instance variable inside of a external java class

    Hi,
    This is N.pradeep. I am a java programmer, and I am new to BEA AquaLogic BPM studio5.7. I have a question regarding how to retrieve an instance variable of BEA Aqua Logic to an external Java Program. i.e. I want to access that BEA instance variable inside of a external java class, and vice versa.

    You can use PAPI or PAPI-WS for accessing BPM instance variable from a Java code, thougt I am not sure how the reverse will be done. Assuming that you are aware aof PAPI-WS and have created the necessary stubs out of the PAPI-WS WSDL using Axis, you can access instance variables using the API's or operations defined therein.
    Thanks and Regards
    Vivek Nandey
    BEA Certified Developer for Integration Solutions
    [email protected]

  • Wrapper classes/ instance variables&methods

    can anyone provide me additional information on the wrapper classes.
    In addition, could someone please provide an explination of the- instance and class (variables+methods)

    Every primitive class has a wrapper class e.g.
    int - Integer
    float - Float
    long - Long
    char - Character
    etc. When a primitive is wrapped it becomes an object and immutable. Primitives are generally wrapped (either to make them immutable) or to be able to add them to the collections framework(sets, maps, lists which can only take objects, not primitives).
    An instance variable is a variable that each copy of the object you create contains, as is an instance method. Each instance you create (each copy of the object) contains its own copy of the variable and method.
    A class variable and method means that no matter how many objects you create, there will be one and only one copy of the variable and method.
    Hope this helps. Also see the java tutorial.

Maybe you are looking for

  • Problems installing Creative Suite 5.5 Design Premium

    I'm trying to install Adobe Creative Suite 5.5 Design Premium on a new computer (Windows 7) from DVD's and receive an Installation Status message at the end of installation that says there were 2 fatal errors, 43 errors, and 43 warnings.  It installs

  • GRN against Account assignment category "Q

    Dear Expert We have created the Purchase order with Account assignment category "Q"Q     Proj. make-to-order and when we take the GRN against the same line item system is pass the following entry Price difference a/c Dr By GR-IR liability a/c Credit

  • ??? char instead to see Greek char in pdf format-standalone ver. 10.1.3.3.1

    Hi, today I just installed the last BIP version standalone (10.1.3.3.1) on my pc. I tried to run a previous report with Greek character but now, ONLY with the pdf format, instead to see the Greek characters I see always the character "?". Using the p

  • How do I publish iWeb site with Cyberduck??

    Hi there, I am trying and trying, but I can't figure it out. Can anybody help me and tell me how to publish an iWeb site with Cyberduck?? Thank you so much! Marc

  • 5 Things MSPs Need to Know about the Windows 10 Upgrade Launch This Wednesday

    This Wednesday, July 29th, Microsoft will officially launch their new Windows 10 operating system for both business and home users.If your non-enterprise end users have either Windows 7 or Windows 8.1 installed on their devices, they are eligible for