Dynamically class creating by using Java Reflection, java.lang.ClassNotFoundException
        Posted  
        
            by rubby
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by rubby
        
        
        
        Published on 2010-04-02T13:03:44Z
        Indexed on 
            2010/04/02
            13:13 UTC
        
        
        Read the original article
        Hit count: 334
        
Hi all; i want to use reflection in java, i want to do that 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.
I wrote that codes but i am always taking to "java.lang.Class.Not.Found.Exception", and i don't know how i can fix it. Can anyone help me?
class class3 {
   public Object dynamicsinif(String className, String fieldName, String value) throws Exception
   {
      Class cls = Class.forName(className,true,null);
      Object obj = cls.newInstance();
      Field fld = cls.getField(fieldName);
      fld.set(obj, value);
      return obj;
  }
  public void writeout3()
  {
      System.out.println("class3");
  }
}
public class Main {
    public static void main(String[] args) throws Exception
    {
           System.out.println("enter the class name : ");
       BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
           String line=reader.readLine();
           String x="Text1";
           try{
              class3 trycls=new class3();
              Object gelen=trycls.dynamicsinif(line, x, "rubby");
              Class yeni=(Class)gelen;
              System.out.println(yeni);
          }catch(ClassNotFoundException ex){
              System.out.print(ex.toString());
          }
    }
}
        © Stack Overflow or respective owner