Java: find caller class

I have a main JFrame that calls class (A) and this class calls another class (B)
In class B, I need a reference to the main JFrame
How to find it?

thanks

+1
source share
3 answers

You can pass a JFrame reference to classes like this

public class SomeFrame extends JFrame { . . . ClassA classA = new ClassA(arg1, arg2..., this, ...); . . . 

In ClassA:

  public class ClassA { private JFrame someFrame; public ClassA(arg1, arg2... JFrame someFrame,...) { this.someFrame = someFrame; . . . ClassB classB = new ClassB(arg1, arg2, this.someFrame, ...); . . . 

In ClassB:

 public class ClassB { private JFrame someFrame; public ClassB(arg1, arg2, JFrame someFrame, ...) { this.someFrame = someFrame; . . . 
+3
source

Passing help seems like the best way.

Another method is to find the current trace of the thread stack and get it from there. This is one of the answers to this question: a Java log that automatically determines the class name of the caller

+2
source

You can use Call Control (IoC) to avoid combining your classes. Specific implementation of IoC Dependency Injection . If you use Java, you can use Spring , so you don't have to worry about implementing dependency injection.

In general, there is a container that takes care of links. In your case, you can instruct the container to insert your main frame into class B so that the frame is accessible from class B.

+1
source

Source: https://habr.com/ru/post/906643/


All Articles