繁体   English   中英

Java类加载器

[英]Java classloader

我需要从目录中的Java文件获取类的方法名称。

   File file=new File("C:/class/");
    try {
      // Convert File to a URL
      URL url = file.toURL();          // file:/c:/class/
      URL[] urls = new URL[]{url};

      // Create a new class loader with the directory
      URLClassLoader loader = new URLClassLoader(urls);

      // Load in the class; Class.childclass should be located in
      // the directory file:/c:/class/
      Class cls = loader.loadClass("Arithmatic.java");
      Method[] methods=cls.getMethods();
      for(Method method:methods){
       System.out.println("Method name:"+method.getName());
      }
  } catch (MalformedURLException e) {
   System.out.println("Exception");
  } catch (ClassNotFoundException e) {
   System.out.println("Class not found exception");
  }

我正在收到ClassNotFoundException

这是正确的做法吗?

任何人都可以提出解决方案的建议...

您不能将.java文件作为类加载。 您应该加载一个.class文件(这意味着应该首先对其进行编译)

loader.loadClass("Arithmatic", true);

如果您没有该类的已编译形式,则可以在运行时使用JavaCompiler对其进行编译

尝试

Class.forName("Arithmatic", true, loader)

代替

loader.loadClass("Arithmatic.java")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM