1

For instance,

// Object 1
SensorMeasurement tempSDSMInfo1 = new SensorMeasurement("temperatureMeasurement", tempSDStruct, "SensorDriver", "TemperatureSensor");

// Object 2
SensorMeasurement tempSDSMInfo2 = new SensorMeasurement("temperatureMeasurement", tempSDStruct, "SensorDriver", "TemperatureSensor");

//Object 3
SensorMeasurement tempSDSMInfo3 = new SensorMeasurement("temperatureMeasurement", tempSDStruct, "SensorDriver", "TemperatureSensor");

Now later in the program , I want to retrieve all the instantiated objects of a particular class ?

I do not want to store them in collection. Is there any other method?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
user-517752
  • 1,188
  • 5
  • 21
  • 54

2 Answers2

3

There is not really any other method. The best practice approach to this problem is to use a factory for SensorMeasurement, or a manager class. Then you will be able to reference them later through the factory or manager and have actions done in the factory or manager as well allowing for a centralized logic center.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • 1
    There is actually another method, via instrumentation, but I doubt it is what he is looking for. – Nikola Yovchev Mar 03 '12 at 21:03
  • @baba : can you explain instrumentation Method, if you can? – user-517752 Mar 03 '12 at 21:21
  • Well, basically, if you use an IDE, you have noticed that there is a possibility, when in debug mode, to see which classes have been loaded by the jvm, how many objects, etc. This is, of course, done on a snapshot at the current time. So if you find a way too hook into the debigging, you are set. Take a look at this: http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html. As it states, instrumentation can give you information about the stats of the current jvm. I personally find that for the problem you described a factory would be sufficient (and less complex) – Nikola Yovchev Mar 03 '12 at 22:41
0

You cannot do this directly in the Java language -- your only option is to store the desired object references in a collection.

For example, you could design your class as such:

public class SensorMeasurement {
  protected static Set<SensorMeasurement> allMeasurements = new HashSet();
  private SensorMeasurement(...) { }
  public static buildSensorMeasurement(String s, Object x, ...) {
    SensorMeasurement sm = new SensorMeasurement(s, x, ...);
    allMeasurements.add(sm);
    return sm;
  }
  public static Set<SensorMeasurement> getAllSensorMeasurements() {
    return new HashSet<SensorMeasurement>(allMeasurements);
  }
}

This way users of your class must use the "buildSensorMeasurement" factory method which will automatically add each instance to the collection which you can use as desired.

maerics
  • 151,642
  • 46
  • 269
  • 291