开发者

Dynamically class creating by using Java Reflection, java.lang.ClassNotFoundException

开发者 https://www.devze.com 2022-12-25 05:23 出处:网络
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 d

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.ClassNotFoundException", 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());    
          }    
    }    
}


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.


A common mistake when trying to instantiate 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消