How to instantiate variable with name from a strin

2019-09-19 20:33发布

问题:

This question already has an answer here:

  • Assigning variables with dynamic names in Java 7 answers

Trying to get a better understanding of Swing and AWT with constructors, but now I have a question about constructors.

Based on whether or not the boolean maximize is true I want to set a new public boolean variable with the same value. Thing is I might need multiple JFrames but I can't have the same public variable name created if true. How do I instantiate a boolean with a name based off of a dynamic string

public void setJframe(JFrame name,  boolean maximize,) {

        if (maximize == true){
            name.setExtendedState(name.getExtendedState()|JFrame.MAXIMIZED_BOTH);
        }
        else {
            name.setLocationRelativeTo(null);
        }
}

Extra clarification

In the if part, it would be something like if it's remotely possible. The parenthesis are meant to indicate the whole variable name and inside a reflection mixed with a string

public boolean (getField(name) + "Max") = maximize;

I'm aware compilers do things a certain way just don't eat me alive if what I put here doesn't reflect that.

回答1:

Reflection views class & field definitions, and enables you to instantiate classes dynamically (by a variable name). It does not allow you to dynamically define fields or classes.

As Hovercraft says, you probably want a reference.

Using a variable enables you to reference the object you want, then set the existing 'property'/ or apply the behavior you want on that.

For example:

public void setupJFrame (JFrame frame, boolean maximize) {
    if (maximize) {
        frame.setExtendedState( frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
    } else {
        frame.setLocationRelativeTo(null);
    }
}

If you need to know on the 'JFrame' what state it is in, you could either subclass it to add a property storing that, or (perhaps better) just make a 'getter' or static 'getter' utility method to answer this using it's existing state.

public static boolean isFrameMaximized (JFrame frame) {
    if ((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH)
        return true;
    return false;
}