我正在创建一个 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 时,它需要一个 Action 监听器,并且在 Action 监听器中调用它的方法。
如果过滤器方法有参数,那么也会将一组文本字段添加到 GUI,以便能够收集参数。
当方法没有参数时,调用工作正常,添加文本字段以及通过这些 TF 捕获参数也很好。
问题是:使用未知大小的列表是否可以将此列表用作反射调用的参数?
图片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:参数数量错误”错误。
最佳答案
一个Object...
其实和一个Object[]
是一样的,所以你需要传递一个Object[]
给成功:
Object[] params = new Object[methodFields.size()];
for (int i = 0; i < methodFields.size(); i++) {
params[i] = Integer.parseInt(methodFields.get(i).getText());
}
关于java - 调用反射方法时参数数量未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54378035/