Java неверное количество аргументов - PullRequest
0 голосов
/ 30 мая 2018

При запуске этого метода я получаю неправильное число аргументов исключение, подобное этому:

Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javafxcyberwind.Participant_MethodsIMPL.execution(Participant_MethodsIMPL.java:85)

Исключение находится в строке комментария, несмотря на то, что введенные аргументы верны, это мой код:

 @Override
 public void execution(String cls, String ip, Object... par) throws InvocationTargetException, RemoteException {
        try {
            URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file:///" + prep)});
            Class<?> c = loader.loadClass(cls);
            Object j = c.newInstance();
            Method[] methods = c.getDeclaredMethods();
            for (Method method : methods) {
                ArrayList<Object> tab = new ArrayList<>();
                if (method.getReturnType() == int.class || method.getReturnType() == String.class || method.getReturnType() == boolean.class || method.getReturnType() == double.class) {
                tab.clear();
                tab.addAll(Arrays.asList(par));
                int i = 0;                    
                HashMap<Integer, File> lif = new HashMap<>();
                File file = null;
                for (Object o : tab) {
                    if (o.getClass().equals(Fichier.class)) {
                        String nomfichier = ((Fichier) o).getNom();
                        file = new File(prep + nomfichier);                            
                        lif.put(i, file);
                    }
                    i++;
                }                 
                for (Map.Entry<Integer, File> entry : lif.entrySet()) {
                    tab.remove(entry.getKey());
                    tab.add(entry.getKey(), entry.getValue());
                }
                k = method.invoke(j, tab.toArray());//line of exception
                if (file != null) {
                    file.delete();
                }
            }
                if (method.getReturnType().toString().equals("class java.io.File")) {
                    tab.clear();
                    tab.addAll(Arrays.asList(par));
                    int i = 0;
                    int t = -1;
                    String nomfichier = null;
                    File file = null;
                    for (Object o : tab) {
                        if (o.getClass().equals(Fichier.class)) {
                            nomfichier = ((Fichier) o).getNom();
                            file = new File(prep + nomfichier);
                            t = i;
                        }
                        i++;
                    }
                    if (t != -1) {
                        tab.remove(t);
                        tab.add(t, file);
                    }
                    k = method.invoke(j, tab.toArray());
                    if (file != null) {
                        file.delete();
                    }
                    fff = nomfichier.replace(nomfichier, cls + "_" + nomfichier);
                    File fres = new File(prep + fff);
                    R.uploadToCloud(fff);
                    Socket s = new Socket(ip, R.getPort());
                    FileInputStream inf = new FileInputStream(fres);
                    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
                    byte buf[] = new byte[1024];
                    int n;
                    while ((n = inf.read(buf)) != -1) {
                        out.write(buf, 0, n);
                    }
                    out.close();
                    inf.close();
                    s.close();
                    fres.delete();
                }
            }
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(Participant_MethodsIMPL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Я могу избежать исключения и заставить его работать, но, как вы видите только для одного файла, переданного в качестве аргумента, это код:

if (method.getReturnType() == int.class || method.getReturnType() == String.class || method.getReturnType() == boolean.class || method.getReturnType() == double.class) {
                tab.clear();
                tab.addAll(Arrays.asList(par));
                int i = 0;
                int t = -1;
                File file = null;
                for (Object o : tab) {
                    if (o.getClass().equals(Fichier.class)) {//means there is an argument of type File
                        String nomfichier = ((Fichier) o).getNom();//getting the file name
                        file = new File(prep + nomfichier);//file that will replace the remote file
                        t = i;
                    }
                    i++;
                }
                if (t != -1) {//replacing the remote file
                    tab.remove(t);
                    tab.add(t, file);
                }
                k = method.invoke(j, tab.toArray());
                if (file != null) {
                    file.delete();
                }
            }

Этот метод вызывается удаленно, поэтому я долженсоздайте новый файл для каждого файла, передаваемого в качестве аргумента, известного, что файлы получены заранее.Проблема заключается в том, что при передаче более одного файла в качестве аргумента, в этом случае, как я могу создать список файлов, где каждый файл имеет идентификатор, равный i, а затем просто просмотреть этот список?Я пытался сделать это с HashMap как наверху, но я продолжаю получать исключение!

1 Ответ

0 голосов
/ 03 июня 2018

Я решил это, просто заменив:

 for (Map.Entry<Integer, File> entry : lif.entrySet()) {
    tab.remove(entry.getKey());
    tab.add(entry.getKey(), entry.getValue());
 }

На:

lif.entrySet().stream().forEach(entry -> tab.set(entry.getKey(), entry.getValue()));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...