2010-03-09 47 views
1

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

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

这是正确的做法吗?

任何机构可以建议的解决方案,请...

回答

2

尝试的

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

代替

loader.loadClass("Arithmatic.java") 
3

不能加载.java文件类。您应该加载.class文件(这意味着它应该先编译)

loader.loadClass("Arithmatic", true); 

如果你没有在编译形式的类,你可以在系统运行时编译JavaCompiler