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

让人想犯罪 __ 提交于 2019-12-19 09:37:47

问题


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());    
          }    
    }    
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2566754/dynamically-class-creating-by-using-java-reflection-java-lang-classnotfoundexce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!