【发布时间】:2019-01-26 11:40:31
【问题描述】:
我正在创建一个根据所选图像特征显示按钮的 GUI。 Let's say image A has the characteristics 1, 2 and 3, so when selected buttons that implements filters for the characteristics 1, 2 and 3 are added to my pannel.
我希望过滤器是可以轻松添加到代码中的方法,因此我使用反射来处理特征,以便为每个图像获取正确的方法。
当一个按钮被添加到 GUI 中时,它需要一个动作监听器,并在动作监听器中调用它的方法。
如果过滤器方法有参数,则一组文本字段也会添加到 GUI 中,以便收集参数。
当方法没有参数时,调用工作正常,添加文本字段以及通过这些 TF 捕获参数也很好。
问题是:使用未知大小的列表是否可以将此列表用作反射调用的参数?
Image 1 shows the GUI with no image selected, when a image is selected the buttons are added and the GUI will look like 2.
public class Filters(){
@Name("Decompose")
public void decompose() {
...decompose the image
}
@Name("Weighted Blur")
public void blurImage(@ParamName("Weight") int weight, @ParamName("Radius") int radius) {
...blur the image
}
}
public class Control(){
public void addFilterFunctions(ArrayList<Method> applicableMethods) {
for(Method m : applicableMethods) {
addButton(m);
}
}
}
public void addButton(Method m) {
JButton newButton = new JButton(m.getAnnotation(Name.class).value());
newButton.addActionListener(genericListener(m, newButton, methodFields));
}
private ActionListener genericListener(Method m, JButton b, ArrayList<JTextField> methodFields) {
return listener ->{
try {
int[] params = new int[methodFields.size()];
for(int i =0; i<methodFields.size();i++) {
params[i] = Integer.parseInt(methodFields.get(i).getText());
}
m.invoke(filters, params);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}
如您所见,我正在从添加到 JPanel 的 textFields 中收集参数,并从中创建一个 int[]。
但似乎调用方法将 Object... objs 作为参数,据我了解,这是一个列表,但我收到“java.lang.IllegalArgumentException: wrong number of arguments”错误。
【问题讨论】:
标签: java reflection