Inheritable instance counter variable

Here's a problem that's been bugging me for a while, and i'm sure there's a simple solution to it that is just escaping me.
I'm developing a pluggable module based system, so i have my base class module with a reference counter counter += 1 in the constructor
My problem is that subclasses of this module don't inherite their own counters (as in counters of the instances of that particular module), instead they just increment the base class's counter.
public abstract class Module {
    //... other stuff
    public static long instanceCount = 0;
    /** Creates a new instance of Module */
    public Module() {
        init();
    public void uninit(){
        Module.instanceCount -= 1;
    public void init(){
        Module.instanceCount += 1;
    //... more stuff
public class TestModule extends Module {
    //... more stuff
    public TestModule() {
        MenuItem = "Test/TestModule";
        ModuleID = "TESTMODULE";
    //... more stuff
public class TestModule1 extends Module {
    //... more stuff
    public TestModule1() {
        MenuItem = "Test/TestModule1";
        ModuleID = "TESTMODULE1";
    //... more stuff
}so, say i created 4 TestModules and 2 TestModule1s
I'm trying to get something like:
Module.instanceCount will equal 6
TestModule.instanceCount == 4
TestModule1.instanceCount == 2
thanks
-Mythagel

Here is an idea. Use the following class to keep track of instances of specific classes:
public class InstanceCounter {
  private static final Integer ONE = new Integer(1);
  private final Map counts = new HashMap();
  public void registerInstance(Class clazz) {
    final Integer oc = (Integer)counts.get(clazz);
    counts.put(clazz, oc == null ? ONE : new Integer(oc.intValue() + 1));
  public int getInstanceCount(Class clazz) {
    final Integer oc = (Integer)counts.get(clazz);
    return oc == null ? 0 : oc.intValue();
}You can then change your Module class to this:
public class Module {
  static final InstanceCounter instanceCount = new InstanceCounter();
  public Module() {
    instanceCount.registerInstance(getClass());

Similar Messages

  • Inheritance - instance variable initialization

    Hi all.
    I have a question regarding inherited instance variables.
    class Animal {
       int weight;
       int age = 10;
    class Dog extends Animal {
       String name;
    class Test {
       public static void main(String[] args) {
          new Dog();
    }This is just an arbitrary code example.
    When new Dog() is invoked, I understand that it's instance variable "name" is give the default
    type value of null before Dog's default constructor's call to super() is invoked.But Im a little perplexed about
    Animals instance variables. I assume that like Dog, Animals instance variables are given their default type values
    of 0 & 0 respectively, before Animals invocation of super(); What im unclear about is that at the point that weight and age are given their default type values, are Dog's inherited weight and age variables set to 0 aswell at that exact moment? Or are Dog's inherited weight and age variables only assigned their values after Animals constructor fully completes because initialization values are only assigned to a classes instance variables after it's call to super().
    Many thanks & best regards.

    Boeing-737 wrote:
    calvino_ind wrote:
    Boeing-737 wrote:
    newark wrote:
    why not throw in some print statements and find out?Super() or this() have to be the very first statement in a constructor..
    Also you cannot access any instance variables until after super or this.
    :-S
    Kind regardsbut if you add the "print" statement in animal constructor, you can easily see what happened to the attributes of Dog ; that s the trick to print "before" super()You can never add a print before super(). It's a rule of thumb, super() and this() must always be the first statements
    in a constructor, whether added implicitly by the compiler or not. In this case there are 2 default constructors (inserted by the compiler), each with a super() invocation. Even if i added them myself and tried to print before super(), the compiler would complain.
    Thanks for the help & regards.you didn't understand what i meant ; take a look at that:
    class Animal {
       int weight;
       int age = 10;
       public Animal() {
           Dog thisAsADog = (Dog) this;
          System.out.println(thisAsADog.name);
          System.out.println(thisAsADog.x);
    class Dog extends Animal {
       String name;
       int x = 10;
    public class Test {
       public static void main(String[] args) {
          new Dog();
    }this way you will know what really does happen

  • Global Counter Variable - Graphical Mapping

    Hi there.
    Can anybody help with implementing a global counter variable in the graphical mapping please.
    I am trying to populate the "SEGMENT" field of an IDoc with the correct sequence, i.e. add 1 for each new segment. The IDoc has several segments, most of which are embedded. I have tried using the "<b>counter</b>" function but this seems to reset back to one for each instance of it being called.
    I would appreciate any pointers.
    Thank you.
    Mick.

    Hi see this for implementation
    <b>defining Global Variables</b>
    ArrayList arrVI;
    int counter =0;
    <b>Initialization Section</b>
    arrVI= new  ArrayList();
    <b>assignment</b>
    arrVI.add(sVI[iLoopCounter]);
    counter++;
    <b>
    fetch Values</b>
    for (int i =0;i<counter;i++)
    result.addValue(arrVI.get(i)+"");
    Mudit

  • Assigning a specific value to the sapscript counter variable

    Hi all,
    I am trying to use the sapscript counter variable in my sapscript but encounter the following warning.
    My code looks like the following:
    /: DEFINE &SAPSCRIPT-COUNTER_0& = 0
    The new counter value is &SAPSCRIPT-COUNTER_0(+)&
    The warning i get when i do the syntax check is:
    Ambiguous symbol &SAPSCRIPT-COUNTER_0&
    What is wrong with my syntax?
    Appreciate any help i can get.

    Hi,
         If i am not wrong you are trying to reinitializing that standard variable. if that is the case one thing, in script we cannot assign values to variable other than at initializing time but here you don't have chance to initialize that variable because that is standard one. More over modifications to standard variable will give some warnings.
    So try to use other than standard one as per your requirement.
    Hope this will help you.
    Regards,
    Aswini.

  • REST API: Create Deployment throwing error BadRequest (The specified configuration settings for Settings are invalid. Verify that the service configuration file is a valid XML file, and that role instance counts are specified as positive integers.)

    Hi All,
    We are trying to access the Create Deployment method stated below
    http://msdn.microsoft.com/en-us/library/windowsazure/ee460813
    We have uploaded the Package in the blob and browsing the configuration file. We have checked trying to upload manually the package and config file in Azure portal and its working
    fine.
    Below is the code we have written for creating deployment where "AzureEcoystemCloudService" is our cloud service name where we want to deploy our package. I have also highlighted the XML creation
    part.
    byte[] bytes =
    new byte[fupldConfig.PostedFile.ContentLength + 1];
                fupldConfig.PostedFile.InputStream.Read(bytes, 0, bytes.Length);
    string a = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    string base64ConfigurationFile = a.ToBase64();
    X509Certificate2 certificate =
    CertificateUtility.GetStoreCertificate(ConfigurationManager.AppSettings["thumbprint"].ToString());
    HostedService.CreateNewDeployment(certificate,
    ConfigurationManager.AppSettings["SubscriptionId"].ToString(),
    "2012-03-01", "AzureEcoystemCloudService", Infosys.AzureEcosystem.Entities.Enums.DeploymentSlot.staging,
    "AzureEcoystemDeployment",
    "http://shubhendustorage.blob.core.windows.net/shubhendustorage/Infosys.AzureEcoystem.Web.cspkg",
    "AzureEcoystemDeployment", base64ConfigurationFile,
    true, false);   
    <summary>
    /// </summary>
    /// <param name="certificate"></param>
    /// <param name="subscriptionId"></param>
    /// <param name="version"></param>
    /// <param name="serviceName"></param>
    /// <param name="deploymentSlot"></param>
    /// <param name="name"></param>
    /// <param name="packageUrl"></param>
    /// <param name="label"></param>
    /// <param name="base64Configuration"></param>
    /// <param name="startDeployment"></param>
    /// <param name="treatWarningsAsError"></param>
    public static
    void CreateNewDeployment(X509Certificate2 certificate,
    string subscriptionId,
    string version, string serviceName, Infosys.AzureEcosystem.Entities.Enums.DeploymentSlot deploymentSlot,
    string name, string packageUrl,
    string label, string base64Configuration,
    bool startDeployment, bool treatWarningsAsError)
    Uri uri = new
    Uri(String.Format(Constants.CreateDeploymentUrlTemplate, subscriptionId, serviceName, deploymentSlot.ToString()));
    XNamespace wa = Constants.xmlNamespace;
    XDocument requestBody =
    new XDocument();
    String base64ConfigurationFile = base64Configuration;
    String base64Label = label.ToBase64();
    XElement xName = new
    XElement(wa + "Name", name);
    XElement xPackageUrl =
    new XElement(wa +
    "PackageUrl", packageUrl);
    XElement xLabel = new
    XElement(wa + "Label", base64Label);
    XElement xConfiguration =
    new XElement(wa +
    "Configuration", base64ConfigurationFile);
    XElement xStartDeployment =
    new XElement(wa +
    "StartDeployment", startDeployment.ToString().ToLower());
    XElement xTreatWarningsAsError =
    new XElement(wa +
    "TreatWarningsAsError", treatWarningsAsError.ToString().ToLower());
    XElement createDeployment =
    new XElement(wa +
    "CreateDeployment");
                createDeployment.Add(xName);
                createDeployment.Add(xPackageUrl);
                createDeployment.Add(xLabel);
                createDeployment.Add(xConfiguration);
                createDeployment.Add(xStartDeployment);
                createDeployment.Add(xTreatWarningsAsError);
                requestBody.Add(createDeployment);
                requestBody.Declaration =
    new XDeclaration("1.0",
    "UTF-8", "no");
    XDocument responseBody;
    RestApiUtility.InvokeRequest(
                    uri, Infosys.AzureEcosystem.Entities.Enums.RequestMethod.POST.ToString(),
    HttpStatusCode.Accepted, requestBody, certificate, version,
    out responseBody);
    <summary>
    /// A helper function to invoke a Service Management REST API operation.
    /// Throws an ApplicationException on unexpected status code results.
    /// </summary>
    /// <param name="uri">The URI of the operation to invoke using a web request.</param>
    /// <param name="method">The method of the web request, GET, PUT, POST, or DELETE.</param>
    /// <param name="expectedCode">The expected status code.</param>
    /// <param name="requestBody">The XML body to send with the web request. Use null to send no request body.</param>
    /// <param name="responseBody">The XML body returned by the request, if any.</param>
    /// <returns>The requestId returned by the operation.</returns>
    public static
    string InvokeRequest(
    Uri uri,
    string method,
    HttpStatusCode expectedCode,
    XDocument requestBody,
    X509Certificate2 certificate,
    string version,
    out XDocument responseBody)
                responseBody =
    null;
    string requestId = String.Empty;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Method = method;
                request.Headers.Add("x-ms-Version", version);
                request.ClientCertificates.Add(certificate);
                request.ContentType =
    "application/xml";
    if (requestBody != null)
    using (Stream requestStream = request.GetRequestStream())
    using (StreamWriter streamWriter =
    new StreamWriter(
                            requestStream, System.Text.UTF8Encoding.UTF8))
                            requestBody.Save(streamWriter,
    SaveOptions.DisableFormatting);
    HttpWebResponse response;
    HttpStatusCode statusCode =
    HttpStatusCode.Unused;
    try
    response = (HttpWebResponse)request.GetResponse();
    catch (WebException ex)
    // GetResponse throws a WebException for 4XX and 5XX status codes
                    response = (HttpWebResponse)ex.Response;
    try
                    statusCode = response.StatusCode;
    if (response.ContentLength > 0)
    using (XmlReader reader =
    XmlReader.Create(response.GetResponseStream()))
                            responseBody =
    XDocument.Load(reader);
    if (response.Headers !=
    null)
                        requestId = response.Headers["x-ms-request-id"];
    finally
                    response.Close();
    if (!statusCode.Equals(expectedCode))
    throw new
    ApplicationException(string.Format(
    "Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}",
                        uri.ToString(),
    Environment.NewLine,
                        (int)statusCode,
                        statusCode,
                        responseBody.ToString(SaveOptions.OmitDuplicateNamespaces)));
    return requestId;
    But every time we are getting the below error from the line
     response = (HttpWebResponse)request.GetResponse();
    <Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Code>BadRequest</Code>
      <Message>The specified configuration settings for Settings are invalid. Verify that the service configuration file is a valid XML file, and that role instance counts are specified as positive integers.</Message>
    </Error>
     Any help is appreciated.
    Thanks,
    Shubhendu

    Please find the request XML I have found it in debug mode
    <CreateDeployment xmlns="http://schemas.microsoft.com/windowsazure">
      <Name>742d0a5e-2a5d-4bd0-b4ac-dc9fa0d69610</Name>
      <PackageUrl>http://shubhendustorage.blob.core.windows.net/shubhendustorage/WindowsAzure1.cspkg</PackageUrl>
      <Label>QXp1cmVFY295c3RlbURlcGxveW1lbnQ=</Label>
      <Configuration>77u/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0NCiAgKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KDQogIFRoaXMgZmlsZSB3YXMgZ2VuZXJhdGVkIGJ5IGEgdG9vbCBmcm9tIHRoZSBwcm9qZWN0IGZpbGU6IFNlcnZpY2VDb25maWd1cmF0aW9uLkNsb3VkLmNzY2ZnDQoNCiAgQ2hhbmdlcyB0byB0aGlzIGZpbGUgbWF5IGNhdXNlIGluY29ycmVjdCBiZWhhdmlvciBhbmQgd2lsbCBiZSBsb3N0IGlmIHRoZSBmaWxlIGlzIHJlZ2VuZXJhdGVkLg0KDQogICoqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioNCi0tPg0KPFNlcnZpY2VDb25maWd1cmF0aW9uIHNlcnZpY2VOYW1lPSJXaW5kb3dzQXp1cmUxIiB4bWxucz0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9TZXJ2aWNlSG9zdGluZy8yMDA4LzEwL1NlcnZpY2VDb25maWd1cmF0aW9uIiBvc0ZhbWlseT0iMSIgb3NWZXJzaW9uPSIqIiBzY2hlbWFWZXJzaW9uPSIyMDEyLTA1LjEuNyI+DQogIDxSb2xlIG5hbWU9IldlYlJvbGUxIj4NCiAgICA8SW5zdGFuY2VzIGNvdW50PSIyIiAvPg0KICAgIDxDb25maWd1cmF0aW9uU2V0dGluZ3M+DQogICAgICA8U2V0dGluZyBuYW1lPSJNaWNyb3NvZnQuV2luZG93c0F6dXJlLlBsdWdpbnMuRGlhZ25vc3RpY3MuQ29ubmVjdGlvblN0cmluZyIgdmFsdWU9IkRlZmF1bHRFbmRwb2ludHNQcm90b2NvbD1odHRwcztBY2NvdW50TmFtZT1zaHViaGVuZHVzdG9yYWdlO0FjY291bnRLZXk9WHIzZ3o2aUxFSkdMRHJBd1dTV3VIaUt3UklXbkFrYWo0MkFEcU5saGRKTTJwUnhnSzl4TWZEcTQ1ZHI3aDJXWUYvYUxObENnZ0FiZnhONWVBZ2lTWGc9PSIgLz4NCiAgICA8L0NvbmZpZ3VyYXRpb25TZXR0aW5ncz4NCiAgPC9Sb2xlPg0KPC9TZXJ2aWNlQ29uZmlndXJhdGlvbj4=</Configuration>
      <StartDeployment>true</StartDeployment>
      <TreatWarningsAsError>false</TreatWarningsAsError>
    </CreateDeployment>
    Shubhendu G

  • Automatically display instance count in caption of text field

    What is the code I use to make the caption of a text field show the instance count of its parent subform?

    There is nothing wrong with your code....but you are assigning a numeric value to a string value and javascript does not seem to like that. If you modify the right side of the equation to be:
    "" + this.parent.index
    Then it seems to work.
    Paul

  • BPM Counter Variable

    FILE1---> XI -->  IDOC
    I have a BPM to receive the File. Do the Transformation and then send to R/3 as requested. This scenario is working fine for me. The only problem I have is, I need to send a mail at the end of the process, saying that how many IDOCs were sent to R/3.
    I have introduced a Counter Variable(SimpleType,Integer) and counting each time an IDOC is created.
    But when I add a new step to send the Counter Variable, I dont even see that variable in the Message variable of the SEnd Step!!!
    What am I doing wrong?

    Hi Mohan,
    you cannot send variables - only messages
    (there's no way to map variable to a message in BPM)
    how can you do your scenario?
    you can do 1:2 mapping
    you can map your file to 2 kinds of messages:
    - idoc
    - message with one field(conuter)
    then map file to those 2 messages and counter has to contain the number of idocs
    then you'll be able to use it in send step:)
    BTW
    if you're not using combined IDOC have a look at my weblog:
    /people/michal.krawczyk2/blog/2005/12/04/xi-idoc-bundling--the-trick-with-the-occurance-change
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions">XI FAQ - Frequently Asked Questions</a>

  • Need to keep track of URL and a count variable

    Can anyone suggest the best way to keep track of a URL and a count variable associated with each URL. I have started using 2 List objects. When I add a URL I also add a 1 in the count List Object. I am using List Objects because I must be able to sort them and search through them.
    Can anyone verify that I am going about this the correct way?
    Thanks

    I would probably use a TreeMap that referenced the counter.

  • Unable to install adobe reader-message :unable to unlock instance count... Please advise. Thx

    unable to install adobe reader-message :unable to unlock instance count... Please advise. Thx

    What is your operating system & version?
    Can you try downloading the installer from http://get.adobe.com/reader/direct/ or http://get.adobe.com/reader/enterprise/ ?

  • Resetting a counter variable

    I am trying to use counter variable "count". The default for "count" is 0 when the program is opened up. I initialize ssd and sumclick to be 0. However once it goes through the formula node, the value for "count" changes to 1 and then the decision loop within the formula node that checks if "count>0" is used.
    My problem is, if I stop the program and then rerun the program without closing and reopenign the program, the value for count continues to be 1, and so my intialization for ssd and sumclick dont happen. Whenever I hit the run button I want count to be 0. I dont want count to remember the 1 from the previous run. How can I do this?
    The VI is below.

    Hi Charles,
    Thanks for answering my question. The pciture I posted is part of a large program. After I posted the question I reworked on the block diagram to create a base level example to try and figure out what was going wrong. Here is the base level example. I tried to get rid of the formula node in this. i just have a while loop and all LV operations. 
    I am trying to generate a random number, take the deviation^2 of the random number from 1 and then keep adding that cumulatively to make SSD. I want my SSD to begin with 0, everytime I stop and re-run the program. VI Attached. Please look at it and tell me. Thanks for the help in advance. 
    Attachments:
    ssd.vi ‏8 KB

  • Page Counter Variable & Captivate 4

    Hello - I can't get a simple page counter variable to work that I snagged from Captain Captivate. When I click to preview, the project will not show. I’ve tried F4 and F12, it will not preview the project. When I click F3, it shows the variable text. I’ve downloaded his sample file, this will not preview either. When I delete the variable the previews work. Any ideas on how to solve this problem or is there another option for creating a simple page counter?
    Thanks!!

    Hello,
    You are talking about a slide number? There is a system variable cpInfoCurrentSlide that gives you that number. To have it on all the slides:
    insert a Text Caption on the first slide, in which you insert this system variable, you can add other text as well
    change the timing of this Text caption to 'for rest of project'
    preview: you will have the slide number on each slide.
    If you want to know more about variables, I posted something for starters. The link is in this blog post:
    Curious about variables in Captivate (4 & 5)?
    And if you want to know more, can recommend a Goober guide by the moderator of this CP-forum, Captiv8r:
    Variables and advanced actions
    Lilybiri

  • [BO XI 3.0] view document instances count is wrong

    If a user does not have the "View document instances" right and there are schedules set up for a particular report to go to other users then the count showing in InfoView is not zero, it counts all the recurring and successful instances even though that user cannot see them!
    I can't see this mentioned in fixed issues manuals for FP1, FP2 or FP3, and I can't find a fixed issues manual for BO XI 3.1
    What we want to happen is when a report is scheduled back to default destination ( i.e. public folders ) then we give the users the "View document instances" right and then the instances count would alert them to click the "view latest instance" option rather than just double clicking as they used to do in V5.1.9, but given that it counts other users schedules as well then that does not seem to be much use to alert users
    I know there is a global option to "open latest instance" but that fails because if there is not a latest instance then it does nothing when you double click
    anybody got any ideas about this?
    regards
    Andrew Dale

    tech support have logged an enhancement request for this for me

  • Instance counter

    is there any other to get an instance counter besides telling it the number of instances in each class? here is one of my class, how could i add it and what would i have to put in my show class?
    public class Cowboys extends Football {
    public int scrimmage () {return passing+rushing+other;}
    public void describe (){
         System.out.println(
              "Total yards the Cowboys gained this week is " +(passing+rushing+other) );
    public static int counter = 1;
    public class Show {........
         public static void main(String argv[]){
              Cowboys c=new Cowboys();
              c.describe();
                                       "The number of class instances in the Cowboys class is ");
              System.out.println(Cowboys.counter); class is ");
    }

    where am i supposed to plug this into, is it the
    Cowboys or in the Show? i tried both and i keep
    getting <identifier> expected in the line private static classCounter;.Something smells bad in the original code you posted. It looks like you have a bunch of code floating about that isn't in either class. That is wrong.

  • Quota still exceeded even after increasing instance count

    I have a personal website on a Shared plan, and while doing some development, I reached the memory quota (512 MB/hour). As I've done other times when this happens, I go to the scale page and increase the instance count to 2, which increases the memory quota
    to 1024 MB/hour.
    My dashboard shows all quota usage in the green, specifically memory usage at 513.2 MB/ 1024 MB. However, my site is still suspended for exceeding usage quota.
    Anyone have this experience or can explain what's going on?

    Hi,
     Hope your Website is up and running now. Azure will Restart the website at the beginning of the next quota interval.
     If you site is still down, I would suggest you contact support and have it looked at by an azure support engineer, since the issue may be at the backend.
     Regards,
     Nithin Rathnakar

  • Initial values to instance & class variable

    I read in the book that instance & class variable definitions are given an initial value depending on the type of information they hold:
    Numeric variable - 0
    Characters - '\0'
    Boolean - false
    Objects - null
    But when I try to compile a class without giving explict value to the variable I get error.
    So why do I need this initial value - if it can't be used any way?

    Sorry� I'll try to make my question clearer.
    As I wrote in my previous message, I read in the book that instance & class variable definitions are given an initial value depending on the type of information they hold:
    Numeric variable - 0
    Characters - '\0'
    Boolean - false
    Objects - null
    From the above I understand that whenever I declare a variable without assigning it a value, it automatically has an initial value.
    For example:
    Class Myclass(){
    Int x;
    Static int z;
    Void fooMyClass(){
    Int y;
    I understand from what I read in the book, both x, y & z - get default values of zero. Is that correct?
    if it is correct, why can't I use these values that were assign as default?

Maybe you are looking for