列出 class 的所有字段,如果它们与所需类型匹配,则将它们放入列表中
To list all the fields of a class and put them in a list if they match a desired type
标题很混乱,但我想要实现的是对我的 class 中的所有(摆动)按钮/标签调用一个方法。
(让它们看起来都相似)
有点像这样:
for(Button btn: components)
btn.setThisTheme();
其中 components[]
是 JComponent-s 的数组。
到目前为止,我已经试过了:
// 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();
几乎可以肯定,你可以不加思索地做你想做的更好的事情。
标题很混乱,但我想要实现的是对我的 class 中的所有(摆动)按钮/标签调用一个方法。 (让它们看起来都相似)
有点像这样:
for(Button btn: components)
btn.setThisTheme();
其中 components[]
是 JComponent-s 的数组。
到目前为止,我已经试过了:
// 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();
几乎可以肯定,你可以不加思索地做你想做的更好的事情。