0

Good day! I have an Apache Netbeans module with several Java classes in it. I'd like to find out when executing a method belonging to an object of, say, class A if another class (class B) had already been instantiated and in this case discover what is this object so that I can call one of its methods from the class A object method. So I am not trying to find out the class of a given object, I am trying to find if there is an object of a given class. Any ideas? Thanks! Erminio.

I didn't try any code because I really have no idea where to start.

Puce
  • 37,247
  • 13
  • 80
  • 152
  • You can put a public static field on A of type B and set it from B's constructor. This sounds like a bad design however. Why do you want to do this? – tgdavies Dec 20 '22 at 20:25
  • Yeah, setting static fields/publishing the object inside the constructor is typically a bad idea - especially since it can easily lead to uninitialized instances being used. – dan1st Dec 20 '22 at 20:33
  • Thanks! I thought about adding a static get method, but the object returned isn't static. Plus I am not the owner of class B, so I'd like to avoid modifying it. – ErminioB Dec 20 '22 at 21:15
  • I just tried with Lookup - my understanding was that the following code should return the ClassB objects, but the collection stays empty: Lookup objectsLookup = Lookup.getDefault(); Template objectsTemplate = new Template(ClassB.class); Result objectsResults = objectsLookup.lookup(objectsTemplate); Collection extends ClassB> objects = objectsResults.allInstances(); – ErminioB Dec 20 '22 at 21:33
  • 1
    You should have another class which coordinates the creation of instances of `A` and `B`. Without more details I can't be more specific. – tgdavies Dec 20 '22 at 21:33
  • I have no idea what `Lookup` is. But please edit your question rather than adding details in comments. – tgdavies Dec 20 '22 at 21:35
  • agree with @tgdavies, it is better to use some coordinator. Another solution is to use reflection and probably `ClassLoader` to check is class loaded or not, due to you cannot edit class B – Rustam Dec 20 '22 at 21:39

0 Answers0