Search code examples
javaclassobjectreflection

Get existing frame from class name without needing command-line arguments


public class Target extends javax.swing.JFrame {
    private Attacker[] FieldIWant;
    /* constructor and other stuff */
    public static void main(String args[]){
        new Target().setVisible(true);
    }
}

Is there a way I can get FieldIWant for the guaranteed only running instance of Target from an Attacker object? I have fully qualified class names for both.

All other methods I have found either only give me a Class object instead of the instance or require command line tampering to enable JDI.

Our class has a final project that involves robots with guns that can’t see each other. Our teacher has slightly encouraged “hacking” the runner, and my petty self wants to give my robot eyes.


Solution

  • Since Target is a subclass of javax.swing.JFrame. you can find all instances of it in the array returned by Frame.getFrames()

    In case there are other instances of Frame or one of its subclasses, you have to iterate over the array and use instanceof to identify the Target instance.

    Then, to access the private field you’d have to use field = Target.class .getDeclaredField("FieldIWant"); and field.setAccessible(true);

    See