Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Writing plugins/modules in Java?

  • 07-02-2007 06:50PM
    #1
    Registered Users, Registered Users 2 Posts: 6,384 ✭✭✭


    Hey guys, Im working on a project for college at the moment and I want to make use of plugins in the project for different features.
    for example, there is some data i want to store, by default i want to store it in a plain text file, but I also want to write a plugin for it so that if you wanted to store the same data in a mysql database instead, you just drop the plugin into the plugins/ directory and restart the app.

    can anyone recommend any good resources (online or books etc..) that cover this subject or offer any pointers on doing this?


Comments

  • Registered Users, Registered Users 2 Posts: 6,384 ✭✭✭kdouglas


    hmmmm... no java guru's around tonight then eh...

    I managed to find a few ok-ish article's online about java class loader's and such, but this one was probably the best resource i found, managed to come up with some sample code based on that to test it,
    ill paste the code below incase anyone every needs a simple enough example of how to do dynamic class loading in java

    First up, the interface, this defines the basic skeleton for the actual implementation of a dynamic class, the dynamic class must implement all of the functions defined in the interface:
    public interface HelloInterface {
    	public void getMessage();
    		
    }
    

    Two example implementations of the interface, pretty basic, but it's just a hello world..
    public class HelloImpl implements HelloInterface {
    	
    	public void getMessage() {
    		System.out.println("Hello, how are you?");
    		
    	}
    }
    
    
    public class HelloImpl2 implements HelloInterface {
    	
    	public void getMessage() {
    		System.out.println("Hello Again!");
    		
    	}
    }
    
    

    the fun part, the actual loading of the class from a file into memory, ready for use:
    import java.io.FileInputStream;
    
    public class ClassManager extends ClassLoader {
    	public ClassManager(){
    	
    	}
    	/**
    	 * Create an instance of a class by loading it from the designated folder/file
    	 * @param dirname
    	 * @param filename
    	 * @return
    	 * @throws ClassNotFoundException
    	 * @throws InstantiationException
    	 * @throws IllegalAccessException
    	 */
    	public Object getInstance(String dirname, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
    		System.out.println("Creating Instance of " + filename);
    		// use this class' loadClass method to read the file
    		String className=this.loadClass(dirname, filename).getName();
    		// use the java ClassLoader.loadClass to actually create an instance of the class
    		return loadClass(className).newInstance();
    		
    	}
    	/**
    	 * Create an instance of a class using filename only, assume current dir
    	 * @param filename
    	 * @return
    	 * @throws ClassNotFoundException
    	 * @throws InstantiationException
    	 * @throws IllegalAccessException
    	 */
    	public Object getInstance(String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
    		return this.getInstance("", filename);
    	}
    	/**
    	 * Load the class from byte code into memory
    	 * @param dirname
    	 * @param classname
    	 * @return
    	 */
    	private Class loadClass(String dirname, String classname){
    		byte classData[];
    		// read from file
    		classData=loadClassFromFile(dirname, classname);
    		// define class
    		Class resultClass=defineClass(null, classData, 0, classData.length);
    		// resolve.....
    		resolveClass(resultClass);
    		System.out.println("Loaded class: " + resultClass.getName());
    		
    		return resultClass;
    		
    	}
    	/**
    	 * load the class byte code into result from the file
    	 * @param dirname
    	 * @param classname
    	 * @return
    	 */
    	private byte[] loadClassFromFile(String dirname, String classname){
    		byte result[];
        	try {
        		System.out.println("Reading from file " + dirname + "/" + classname);
        	    
        	    FileInputStream fi = new FileInputStream(dirname + "/" + classname);
        	    result = new byte[fi.available()];
        	    fi.read(result);
        	    System.out.println("File Read!");
        	    return result;
        	} catch (Exception e) {
        		e.printStackTrace();
        	    return null;
        	}
    	}
    }
    
    

    and finally, an example implementation of all the above
    this will read any files in the ./plugins/ directory and load them into memory as HelloInterface object and calling the getMessage function on each
    import java.io.File;
    import java.io.FileInputStream;
    
    
    
    public class HelloTest extends ClassLoader {
    	public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    		new HelloTest();
    	}
    
    	public HelloTest() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    		HelloInterface hi;
    		ClassManager cm=new ClassManager();
    		// loop through the plugins directory and load each of the classes in order
    		for(String file: getDirContents("plugins")){
    			System.out.println("Attempting to load:" + file);
    			// load an instance of this class
    			hi=(HelloInterface) cm.getInstance("plugins", file);
    			// print out the message
    			hi.getMessage();
    		}	
    		
    	}
    	// get the contents of a directory as an array
    	public String[] getDirContents(String dirname){
    		File dir=new File(dirname);
    		return dir.list();
    	}
    }
    
    


Advertisement