mercredi 5 juin 2019

Imported class calling methods from importer

I have an external device that I want to test. For that purpose I'm implementing a Java desktop application with a GUI with which you can add different test scripts made in Java as well.

The idea is that the application should provide all the components needed for the script to use, such as communications with the device, utils, etc. For now I'm able to load and compile dynamically the script and run a certain method from the imported class, like so:

Importer application

public class TestLoader 
{
    public void load(String classFile) throws Exception
    {
        System.out.println("Loading class: " + classFile + ".class");

        // create FileInputStream object
        File file = new File(mPath);

        // Convert File to a URL
        URL url = file.toURI().toURL();
        URL[] urls = new URL[]{url};

        // Create a new class loader with the directory
        ClassLoader cl = new URLClassLoader(urls);

        // Load in the class; MyClass.class should be located in
        // mTest + /org/testing/
        Class cls = cl.loadClass("org.testing.Test");
        Object obj = cls.newInstance();
        Method method = cls.getDeclaredMethod("run");
        method.invoke(obj);
    }
}

Imported class

package org.testing;

public class Test 
{
    public void run() 
    {
        System.out.println("Hi");
    }
}


Having this, now I want that the imported class calls a method within the application to, let's say, send something to the device and update the GUI with the result:

Importer application

package org.comms;

public class DeviceAccessor
{
    public void Transmit(String message)
    {
        // Transmit message to device

        // Update the GUI
    }
}

Imported class

package org.testing;

import ??

public class Test 
{
    public void run() 
    {
        Transmit("Hi");
    }
}

I thought of having this DeviceAccessor compiled as an external framework so that both the application and the test import it. But I'd like to know if it's possible to have it embedded in the application.





Aucun commentaire:

Enregistrer un commentaire