如何从字符串实例化变量名称? [英] How to instantiate variable with name from a string?

查看:289
本文介绍了如何从字符串实例化变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用构造函数更好地了解Swing和AWT,但现在我对构造函数有一个问题。

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

根据布尔值最大化 true 我想设置一个具有相同值的新的公共布尔变量。事情是我可能需要多个JFrames,但我不能有相同的公共变量名称创建如果真。 如何使用基于动态字符串的名称实例化布尔值

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);
        }
}

额外澄清

if 部分中,如果它是远程可能的话。
括号用于表示整个变量名称以及与字符串混合的反射

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.

推荐答案

反射视图类&字段定义,并允许您动态实例化类(通过变量名)。它不允许你动态定义字段或类。

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.

Hovercraft说,你可能想要一个引用

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.

例如:

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



如果你需要知道'JFrame'状态,你可以子类化它添加一个属性存储,或者(或许更好)只是使用一个'getter'或静态的getter'实用方法来回答这个使用它的现有状态。

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

这篇关于如何从字符串实例化变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆