General way to reference parent class in Java

I have code that needs to be reused in multiple Java applications. This code implements a GUI, which, in turn, must have access to some static variables and methods from the calling class. These variables and methods are always called the same in all applications. Is there a general way to get the handle of the calling class in Java, so the code for the "someGUI" class can remain intact and actually comes from the same source file for all different applications?

Minimum working example:

import javax.swing.*;

class test {
  static int variable = 123;
  public static void main(String[] args) {
    someGUI sg = new someGUI();
    sg.setVisible(true);
  }
}

class someGUI extends JFrame {
  public someGUI() {
    System.out.println(String.format("test.variable = %d", test.variable));
  }
}

How can I “generate” a reference to “test” in test.variable to always refer to the calling class? This is not a “super” class, at least using super.variable does not work.

+4
2

-, , . SomeGUI , .

, , , . , :

class Test {
    static int variable = 123;

    public static void main(String[] args) throws Exception {
        SomeGUI sg = new SomeGUI();
    }

    static class SomeGUI extends JFrame {

        public SomeGUI() throws Exception {
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            // stackTrace[0] is getStackTrace(), stackTrace[1] is SomeGUI(),
            // stackTrace[2] is the point where our object is constructed.
            StackTraceElement callingStackTraceElement = stackTrace[2];
            String className = callingStackTraceElement.getClassName();
            Class<?> c = Class.forName(className);
            Field declaredField = c.getDeclaredField("variable");
            Object value = declaredField.get(null);
            System.out.println(String.format("test.variable = %d", value));
        }
    }
}

test.variable = 123.

, . .

, , . , , .

+1
  • somGUI , GUI JFrame. super(), JVM "" JFrame, , .
  • "" .
0

All Articles