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 编译它

关于Java类加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2407581/

相关文章:

java - Eclipse/OSGI、Java 11、JAXB 和类加载器

java - 获取动态生成的java类的源代码

java - 当我们在eclipse Debug模式下修改某个对象时,类加载是如何发生的

java - 在 SWT 中设置颜色

java - JUnit 只记录失败?

java - 反射 - 从数据库值确定调用方法和参数

java - 使用特定的 ClassLoader 获取 CtClass

java - 用于访问 LinkedIn 数据的 Spring Boot 应用程序

Java:PriorityQueue 初始化

java - 应用程序决定jar版本