mardi 4 août 2015

refresh runtime with Executors

(1) This code runs the main method within a class (Code (3)) and then writes the console output to a file:

        Class runnable;
        File output;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(byteArrayOutputStream);
            PrintStream old = System.out;
            System.setOut(ps);
            Method method = runnable.getMethod("main", String[].class);
            method.invoke(null, (Object) null);
            System.out.flush();
            System.setOut(old);
            String consoleOutput = byteArrayOutputStream.toString();
            Files.write(output, consoleOutput);
            Logger.getLogger(Autorunner.class.getName()).log(Level.INFO, "Output written to: {0}", output.getAbsolutePath());
            runnable = runnable.getClassLoader().loadClass(runnable.getName());
        } catch (NoSuchMethodException | SecurityException | IOException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException ex) {
            Logger.getLogger(Autorunner.class.getName()).log(Level.SEVERE, null, ex);
        }

(2) This code executes the above code every 5 seconds:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Autorunner(Test.class, new File("Stuff.txt")), 0, 5, TimeUnit.SECONDS);

(3) This code writes stuff to the console:

System.out.println("stuff");

The problem I'm having is that when I update and compile Code (3) from say System.out.println("stuff"); to System.out.println("More Stuff");, then Code (2) still writes stuff to the console instead of More Stuff. I thought since I had the line runnable = runnable.getClassLoader().loadClass(runnable.getName()); in Code (1) it wouldn't be an issue...



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire