It is a short side project away from the OpenCV and Processing thread. In this example, I would like to see if I can load an external class within a Processing sketch. The structure of the program is:
Main program
TestLoad001
import java.lang.reflect.Method; void setup() { size(640, 480); } void draw() { background(0); } void mousePressed() { MyLoader ldr = new MyLoader(); Class myObj = ldr.load("MyTest"); Object oo; try { oo = myObj.newInstance(); println("Class name: " + oo.getClass().getName()); Method m = oo.getClass().getMethod("ShowMe"); println("Method name: " + m.getName()); m.invoke(oo); } catch (Exception e) { e.printStackTrace(); } } |
Loader class
MyLoader (a subclass of ClassLoader)
import java.net.URL; import java.net.URLConnection; import java.io.ByteArrayOutputStream; public class MyLoader extends ClassLoader { public MyLoader() { super(); } public Class load(String _c) { try { String url = "file:" + dataPath(_c + ".class"); URL addr = new URL(url); URLConnection conn = addr.openConnection(); InputStream in = conn.getInputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int num = in.read(); while (num != -1) { buf.write(num); num = in.read(); } in.close(); byte [] data = buf.toByteArray(); return defineClass("MyTest", data, 0, data.length); } catch (Exception e) { e.printStackTrace(); } return null; } } |
External class (compiled and placed inside the data folder)
MyTest
public class MyTest { public MyTest() { System.out.println("MyTest object instance created."); } public void ShowMe() { System.out.println("ShowMe method called."); } } |