ClassNotFoundException动态

ClassNotFoundException动态

本文介绍了使用Java Reflection,java.lang.ClassNotFoundException动态创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我编写了这些代码,但我总是选择 java.lang .ClassNotFoundException ,我不知道如何修复它。
任何人都可以帮助我吗?

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将抛出 ClassNotFoundException ,并且具有该名称的类不能位于类路径中。您应确保您尝试实例化的类位于类路径上,并且您使用其完全限定名称(例如: java.lang.String 而不是字符串

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)

编辑:您不需要使用3 arg forName Class 上的方法。相反,使用1 arg forName ,它只接受您传入的类名。

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.

这篇关于使用Java Reflection,java.lang.ClassNotFoundException动态创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:07