开发者

Java: Find Caller Class

I have a main JFrame that calls a cl开发者_StackOverflow中文版ass(A) and that class calls another class (B)

In Class B I need a refrence to main JFrame

How to find that?

Thanks


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜