使用 Java Reflection、java.lang.ClassNotFoundException 动态创建类

发布于 2024-08-28 00:47:23 字数 1364 浏览 7 评论 0原文

我想在java中使用反射,我想做第三个类将从控制台读取类的名称作为字符串。读取类的名称后,它将自动动态(!)生成该类并调用其 writeout 方法。如果该类不是从输入中读取的,则不会对其进行初始化。

我写了这些代码,但我总是使用“java.lang.ClassNotFoundException”,而且我不知道如何修复它。 谁能帮助我吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你的手,一向走下去 2024-09-04 00:47:23

当您尝试反射类名并且在类路径中找不到具有该名称的类时,Java 将抛出 ClassNotFoundException 。您应该确保您尝试实例化的类位于类路径上,并且使用其完全限定名称(例如:java.lang.String 而不仅仅是 String

编辑:您不需要在 Class 上使用 3 arg forName 方法。相反,请使用 1 arg forName,它仅采用您传入的类名。

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.

望喜 2024-09-04 00:47:23

尝试通过反射实例化对象时的一个常见错误是仅传递类名,而不是完全限定名称。换句话说,使用“String”而不是“java.lang.String”将不起作用。

另外,请注意,您的代码仅适用于具有默认(或无参数)构造函数的类。如果您遇到一个在其构造函数中需要参数的类,则对“cls.newInstance()”的调用将会失败。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文