Dynamically creating classes using Java Reflection, java.lang.ClassNotFoundException

I want to use reflection in java, I want the third class to read the class name as String from the console. After reading the class name, it automatically and dynamically (!) Generates this class and calls its method writeout. If this class is not read from input, it will not be initialized.

I wrote these codes, but I always accept " java.lang.ClassNotFoundException", and I don't know how I can fix this. Can anybody 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());    
          }    
    }    
}
+3
source share
2 answers

Java ClassNotFoundException, , . , , , (ex: java.lang.String String)

EDIT: 3 arg forName Class. 1 arg forName, , .

+6

, . , "String" "java.lang.String" .

, , ( ). , , "cls.newInstance()" barf.

+4

Source: https://habr.com/ru/post/1739596/


All Articles