Java: Find Caller Class

2019-08-05 13:18发布

问题:

I have a main JFrame that calls a class(A) and that class calls another class (B)
In Class B I need a refrence to main JFrame
How to find that?

Thanks

回答1:

You can pass a reference of the JFrame to the classes like so

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;
 .
 .
 .


回答2:

Passing a reference seems like the best way.

Another method is to look up the current thread's stack trace and get it from there. It is one of the answers to this question: Java logger that automatically determines caller's class name



回答3:

You can use Inversion of Control (IoC) design pattern to avoid coupling your classes. A specific implementation of IoC is Dependency Injection. If you are using Java you can use Spring so you don't have to worry about the implementation of dependency injection.

In general terms there is a container that takes care of the references. In your case you can instruct the container to inject your main Frame to class B so the Frame will be accessible from class B.



标签: java class