views:

354

answers:

3

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());    
          }    
    }    
}
+4  A: 

Java will throw a ClassNotFoundException when you try to reflect on a class name and a class with that name cannot be located in the classpath. You should ensure that the class you are trying to instantiate is on the classpath and that you use its fully qualified name (ex: java.lang.String instead of just String)

EDIT: you do not need to use the 3 arg forName method on Class. Instead, use the 1 arg forName that takes only the class name that you are passing in.

akf
+2  A: 

A common mistake when trying to instanciate object through reflection is to pass just the class name, not the fully qualified name. In other words, using "String" instead of "java.lang.String" will not work.

Also, be aware that your code will only work for classes that have a default (or no arg) constructor. If you run into a class that requires arguments in it's constructor, your call to "cls.newInstance()" will barf.

Todd R
A: 

the same error is continue , ı tried and changed String to java.lang.string but it's the same error

trendyy