为了账号安全,请及时绑定邮箱和手机立即绑定

如何将字段转换为指定类型

如何将字段转换为指定类型

慕尼黑8549860 2023-03-17 13:49:46
我正在尝试使用 Swing 创建一个用户界面,但我不想手动将每个组件包含在我的组件数组中。到目前为止,我得到的最好的尝试抛出了一个异常,这是我不能真正拥有的。for (Field f : this.getClass().getFields()) {    if (f.getType().isAssignableFrom(JComponent.class)) {        JComponent field = (JComponent) f.get(JComponent.class);        components.add(field);    }}我希望我展示的代码不包含任何异常,但确实如此。有没有办法在没有异常风险的情况下做到这一点?
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

reflect当不一定需要时,不应使用离子用法。大多数时候,创建 a 的原因component是将其添加到容器中。将其添加到那里后,您可以使用方法轻松地从容器中询问他们Container#getComponents。


检查这个例子:


JButton loadButton = new JButton("load");

JButton saveButton = new JButton("save");

JPanel panel = new JPanel();

panel.add(loadButton);

panel.add(saveButton);

for (Component component : panel.getComponents()) {

    // ...

}

为了给你更多的帮助,你必须告诉我们你想用这个数组做什么。我的意思是,你想在哪里使用它?


如果您坚持使用它,则for应该是:


for (Field f : this.getClass().getDeclaredFields()) {

    if (JComponent.class.isAssignableFrom(f.getType())) {

        JComponent field = (JComponent) f.get(this);

        components.add(field);

    }

}


查看完整回答
反对 回复 2023-03-17
  • 1 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信