java - 列出类的所有字段,如果它们与所需类型匹配,则将它们放入列表中

标签 java class nullpointerexception field gettype

标题很困惑,但我想要实现的是调用类中所有( Swing )按钮/标签的方法。 (让它们看起来都很相似)

有点像这样:

for(Button btn: components)
  btn.setThisTheme();

其中 components[] 是 JComponent 数组。 到目前为止我已经尝试过:

    // at beginning of class
    private LinkedList<JComponent> components = new LinkedList<>();
    private Field[] fields = ToDo.class.getDeclaredFields().length;


   // in constructor
   for (Field field: fields) {
            if(field.getType() == JComponent.class) { 
                components.add(field); // how to do this? 
// field is a Field and i need to convert it into the variable it represents...
            }
        }

最佳答案

您正在创建一个 null 数组。

private Field[] fields = new Field[ToDo.class.getDeclaredFields().length];

您应该能够直接使用 getDeclaredFields 返回的数组。

private Field[] fields = ToDo.class.getDeclaredFields();

几乎可以肯定,您无需反射(reflection)就可以做得更好。

关于java - 列出类的所有字段,如果它们与所需类型匹配,则将它们放入列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59653211/

相关文章:

java - 汇流插件

java - 优化java代码以更少的时间对数组/数组列表进行排序

JavaScript 类型错误 : cannot read property of undefined

java - 什么是NullPointerException,我该如何解决?

java - 什么是 NullPointerException,我该如何解决?

java - 由于 Graphics g 初始化而导致 AWT-EventQueue-0 NullPointerException

java - 无法识别的虚拟机选项 ' ExplicitGCInvokesConcurrentAndUnloadsClasses'

java - 使用 MigLayout 调整组件和字体的大小

jquery - 删除/添加链接类 onclick

php - MySQL 连接 : globally or in object?