标题很困惑,但我想要实现的是调用类中所有( 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/