Generate java class and call it's method dynamically

Posted by Jacob on Stack Overflow See other posts from Stack Overflow or by Jacob
Published on 2010-03-24T21:30:37Z Indexed on 2010/03/24 21:33 UTC
Read the original article Hit count: 258

Filed under:
|

package reflection;

import java.io.*;

import java.lang.reflect.*;

class class0 { public void writeout0() { System.out.println("class0"); } }

class class1 { public void writeout1() { System.out.println("class1"); } }

class class2 { public void writeout2() { System.out.println("class2"); } }

class class3

{

public void run()

{

try

{    

    BufferedReader reader= new BufferedReader(new InputStreamReader

(System.in));

      String line=reader.readLine(); 

      Class cls=Class.forName(line);
             //define method here



}

catch(Exception ee)

{

System.out.println("here "+ee);

}

} public void writeout3() { System.out.println("class3"); } }

class class4 { public void writeout4() { System.out.println("class4"); } }

class class5 { public void writeout5() { System.out.println("class5"); } }

class class6 { public void writeout6() { System.out.println("class6"); } }

class class7 { public void writeout7() { System.out.println("class7"); } }

class class8 { public void writeout8() { System.out.println("class8"); } }

class class9 { public void writeout9() { System.out.println("class9"); } }

class testclass {

public static void main(String[] args) {

   System.out.println("Write class name : ");

    class3 example=new class3();

    example.run();
}

}

Question is ; third class will read the name of the class as String from console. Upon reading the name of the class, it will automatically and dynamically generate that class and call its writeout method.If that class is not read from input, it will not be initialized.

but I can't continue any more ; i need to more something for 3.class, what can i do?

Thanks;

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection