0

I am trying to load an class with specific url and invoke methods inside that class by passing same values to them.

Not exactly sure how to do that.

My url looks something like this: "file:/C:/Users/Retro/Desktop/best-project-2/mutants/traditional_mutants/Complex_cconvolve(Complex,Complex)/AOIS_136/FFT.class"

I tried to load class like this

package com.company.fileIterator;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;



public class CallMutant {
    public static void main(String[] args) throws IOException {
        FolderIterator folderTestRunner = new FolderIterator();
        List<String> list = folderTestRunner.getFilesPath();

        URL url;
        try{
            url = new URL("file:///"+list.get(5));
            System.out.println(url);
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("FFT");
            Object o = clazz.newInstance();
            System.out.println(o.toString());
        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }


    }

}

and the main goal is to load multiple classes witch has the same name and methods.

Thanks for any help.

Imposter
  • 31
  • 9

3 Answers3

1

I don't understand your point. Why do you don't compile a jar file of this class file and include it in your project as dependency (like see here)? Using the class-loader and reflection for such a case is slow and unsafe.

Koenig
  • 54
  • 4
  • I have like 100 + class list, that I need to load and get methods from them. All these classes are with some kind of mistake in them. And I need to get the results of the methods and compare theme to the good results from original class so I can find all the bad classes. I don't care for safety and all, I just need to get this done somehow. I tried lots of examples, just can't do this by myself :( by the way all classes have the same name and methods. But they are in different folders and some of them require different inputs. All I managed to do get the list of locations of class files. – Imposter Jun 09 '18 at 18:53
  • This https://stackoverflow.com/questions/6219829/method-to-dynamically-load-java-class-files?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa example works exellent. – Koenig Jun 09 '18 at 19:07
  • I get this error with this: `java.lang.ClassNotFoundException: FFT at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at com.company.fileIterator.CallMutant.main(CallMutant.java:31)` – Imposter Jun 09 '18 at 19:35
  • Is FFT in the default package? You have to specify the full qualified name on loading. – Koenig Jun 09 '18 at 19:49
  • well I think FFT has no package at all. Is it possible? I'll paste all code of FFT file in new post. and my code for calling it. – Imposter Jun 09 '18 at 19:54
  • also FTT is outside my code. It is in marked directories like so: dir/dir/FTT.java https://prnt.sc/jt24u7 – Imposter Jun 09 '18 at 20:02
  • When FFT has no package, it has the default package. – Koenig Jun 09 '18 at 20:05
  • What should I do here? – Imposter Jun 09 '18 at 20:27
  • Please test your example with a different class file. Like the class file of your main application. – Koenig Jun 09 '18 at 20:38
0

FTT.class also I have the same file just with extension java

public class FFT {
    public FFT() {
    }

    public static Complex[] fft(Complex[] var0) {
        int var1 = var0.length;
        if (var1 == 1) {
            return new Complex[]{var0[0]};
        } else if (var1 % 2 != 0) {
            throw new RuntimeException("N is not a power of 2");
        } else {
            Complex[] var2 = new Complex[var1 / 2];

            for(int var3 = 0; var3 < var1 / 2; ++var3) {
                var2[var3] = var0[2 * var3];
            }

            Complex[] var11 = fft(var2);
            Complex[] var4 = var2;

            for(int var5 = 0; var5 < var1 / 2; ++var5) {
                var4[var5] = var0[2 * var5 + 1];
            }

            Complex[] var12 = fft(var4);
            Complex[] var6 = new Complex[var1];

            for(int var7 = 0; var7 < var1 / 2; ++var7) {
                double var8 = (double)(-2 * var7) * 3.141592653589793D / (double)var1;
                Complex var10 = new Complex(Math.cos(var8), Math.sin(var8));
                var6[var7] = var11[var7].plus(var10.times(var12[var7]));
                var6[var7 + var1 / 2] = var11[var7].minus(var10.times(var12[var7]));
            }

            return var6;
        }
    }

    public static Complex[] ifft(Complex[] var0) {
        int var1 = var0.length;
        Complex[] var2 = new Complex[var1];

        int var3;
        for(var3 = 0; var3 < var1; ++var3) {
            var2[var3] = var0[var3].conjugate();
        }

        var2 = fft(var2);

        for(var3 = 0; var3 < var1; ++var3) {
            var2[var3] = var2[var3].conjugate();
        }

        for(var3 = 0; var3 < var1; ++var3) {
            var2[var3] = var2[var3].times(1.0D / (double)var1);
        }

        return var2;
    }

    public static Complex[] cconvolve(Complex[] var0, Complex[] var1) {
        if (var0.length != var1.length) {
            throw new RuntimeException("Dimensions don't agree");
        } else {
            int var2 = var0.length;
            Complex[] var3 = fft(var0);
            Complex[] var4 = fft(var1);
            Complex[] var5 = new Complex[var2];

            for(int var6 = 0; var6 < var2; ++var6) {
                var5[var6] = var3[var6].times(var4[var6]);
            }

            return ifft(var5);
        }
    }

    public static Complex[] convolve(Complex[] var0, Complex[] var1) {
        Complex var2 = new Complex(0.0D, 0.0D);
        Complex[] var3 = new Complex[2 * var0.length];

        int var4;
        for(var4 = 0; var4 < var0.length; ++var4) {
            var3[var4--] = var0[var4];
        }

        for(var4 = var0.length; var4 < 2 * var0.length; ++var4) {
            var3[var4] = var2;
        }

        Complex[] var6 = new Complex[2 * var1.length];

        int var5;
        for(var5 = 0; var5 < var1.length; ++var5) {
            var6[var5] = var1[var5];
        }

        for(var5 = var1.length; var5 < 2 * var1.length; ++var5) {
            var6[var5] = var2;
        }

        return cconvolve(var3, var6);
    }

    public static void main(String[] var0) {
        int var1 = Integer.parseInt(var0[0]);
        Complex[] var2 = new Complex[var1];

        int var3;
        for(var3 = 0; var3 < var1; ++var3) {
            var2[var3] = new Complex((double)var3, 0.0D);
            var2[var3] = new Complex(-2.0D * Math.random() + 1.0D, 0.0D);
        }

        System.out.println("x");
        System.out.println("-------------------");

        for(var3 = 0; var3 < var1; ++var3) {
            System.out.println(var2[var3]);
        }

        System.out.println();
        Complex[] var8 = fft(var2);
        System.out.println("y = fft(x)");
        System.out.println("-------------------");

        for(int var4 = 0; var4 < var1; ++var4) {
            System.out.println(var8[var4]);
        }

        System.out.println();
        Complex[] var9 = ifft(var8);
        System.out.println("z = ifft(y)");
        System.out.println("-------------------");

        for(int var5 = 0; var5 < var1; ++var5) {
            System.out.println(var9[var5]);
        }

        System.out.println();
        Complex[] var10 = cconvolve(var2, var2);
        System.out.println("c = cconvolve(x, x)");
        System.out.println("-------------------");

        for(int var6 = 0; var6 < var1; ++var6) {
            System.out.println(var10[var6]);
        }

        System.out.println();
        Complex[] var11 = convolve(var2, var2);
        System.out.println("d = convolve(x, x)");
        System.out.println("-------------------");

        for(int var7 = 0; var7 < var11.length; ++var7) {
            System.out.println(var11[var7]);
        }

        System.out.println();
    }
}

CallMutant.java //

full link

list.get(5) = C:\Users\Retro\Desktop\best-project-2\mutants\traditional_mutants\Complex_cconvolve(Complex,Complex)\AOIS_136\FFT.class package com.company.fileIterator;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;



public class CallMutant {
    public static void main(String[] args) throws IOException {
        FolderIterator folderTestRunner = new FolderIterator();
        List<String> list = folderTestRunner.getFilesPath();

        URL url;
        try{
            url = new URL("file:///"+list.get(5));
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("FFT");
            Object o = clazz.newInstance();
            System.out.println(o.toString());
        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }


    }

}
Imposter
  • 31
  • 9
0

Ok, so what I finally did used reflections. I created a temp file, copied all the code from the original FFT class, changed class name to be the same as file name and finally compiled the new file and invoke the necessary methods.

That did the job.

public class CallMutant {

    public static void main(String[] args) throws IOException {
        // get mutant list
        List<String> list = FolderIterator.getFilesPath();
        for (int i = 0; i < list.size(); i++) {
            System.out.println("Iter: "+ i);
            File source = new File(list.get(i));
            File dest = File.createTempFile("FFT", ".java");
            dest.deleteOnExit();
            System.out.format("Canonical filename: %s\n", dest.getCanonicalFile());

            //copy file using Stream
            try {
                copyFileUsingStream(source, dest);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // generate the source code, using the source filename as the class name
            String classname = dest.getName().split("\\.")[0];
            Path path = Paths.get(String.valueOf(dest));
            Charset charset = StandardCharsets.UTF_8;

            String content = new String(Files.readAllBytes(path), charset);
            content = content.replaceAll("public class FFT", "public class " + classname);
            Files.write(path, content.getBytes(charset));

            // compile the source file
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
            File parentDirectory = dest.getParentFile();
            fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(parentDirectory));
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(dest));
            compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
            fileManager.close();

            // load the compiled class
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{parentDirectory.toURI().toURL()});
            Class<?> helloClass = null;
            try {
                helloClass = classLoader.loadClass(classname);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                System.out.println("No class found");
            }

            // call a method on the loaded class
            Method helloMethod = null;
            try {
                Complex[] params2 = new Complex[1];
                helloMethod = helloClass.getDeclaredMethod("main", String[].class);
            } catch (NoSuchMethodException e) {
                System.out.println("No Method found");
                e.printStackTrace();
            }
            try {
                String[] params = {"1"};
                helloMethod.invoke(helloClass.newInstance(), (Object) params);
            }catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
                e.printStackTrace();
            }
        }
    }
    private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            os.write("import com.company.originals.Complex;\n".getBytes());
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
}
Imposter
  • 31
  • 9