I need to ("command pattern"-like) call classes which names I know to create certain objects.
Then the objects (kept in an array) should call the same name methods (doing something different for different objects, etc.) So you will be effectively calling an object's method based on an index.
I thought something like that you could do in Java easily, but apparently there may be something I might be missing here.
Short code examples of both classes with comments are included.
How can you do this?
// - - - - - - - - - - - - - - - -- - - - - - -
import java.util.*;
class K0{ String azKNm; int iIx; // __ public K0(){ this.azKNm = "K0"; this.iIx = 0; } // __ public String doIt(){ // __ An exception is simulated and caught to look at the call Stack (new Exception((new Date()).toString())).printStackTrace(); // __ you do return the internal value, though return(toString()); } // __ public String toString(){ return(azKNm + "|" + iIx); } }
// - - - - - - - - -
public class TestKn04{ public static void main(String[] azArgs){ K0 K; Class KX = null; Object Obj = null;
// __ This, of course :-), works K = new K0(); System.err.println("- - - - - - - - - - - - - - - - - -"); System.err.println("K.doIt()"); System.err.println(K.doIt());
// __ Works fine too try{ KX = Class.forName("K0"); } catch(ClassNotFoundException KNFX){ KNFX.printStackTrace(); }