Java bits

I'm very pleased with this bit of code. It illustrates dynamically loaded classes. I had a struggle finding a decent example and had to do a lot of trial and error. It is all very simple when you know how.
  1. Create and compile some classes with a method "partyPiece()" that returns a string
    • public class Wizzer{
        public String partyPiece(){return "Whizzzzeeeerrrr!";}
    • public class Cracker{
        public String partyPiece(){return "BANG!";}
  2. Compile this class then run it with the names of those classes on the command line
    •   java TestParty Cracker Wizzer Cracker

import java.lang.reflect.*;

    public class TestParty{

       public static void main(String[] args){
         Class c;
         Method m;
         Constructor con;
         Object pt = null;
         Object[] oa = null;  // we don't use oa and ca in this
         Class[] ca = null;   // program except as dummy arguments.

         // run through list of class names
         // as provided on the command line
            int i=0;
            while (i < args.length){

            // find and load the class dynamically
               c = Class.forName(args[i]);

            // and locate the method we want
               m = c.getMethod("partyPiece",ca);

            // create an instance
               con = c.getConstructor(ca);
               pt = con.newInstance(oa);

            // see what happens if we invoke the method
            // NB the partyPiece() method will return a string
               System.out.println(i+" "+m.invoke(pt,oa));

            // bump loop
             catch(Exception e){System.out.println("ERROR "+e.getMessage());}

Site contents ©