2013-04-07 77 views
0

我想从文件系统上的路径获取类,并从中获取字节。我尝试了下面的内容,但没有成功。这应该只是打印出现在的名字。如果任何人有任何想法如何做我在做什么,请让我知道。它甚至有可能比这更容易...从类读取字节

public class Driver { 
public static void main(String[] args) throws Exception { 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Enter the path of the class: "); 
    String from = br.readLine(); 
    System.out.print("Enter the path to save the .txt file (with bytes): "); 
    String to = br.readLine(); 
    Class clazz = getClassFromPath(from); 
    System.out.println("Loaded <" + clazz.getName() + "> successfully!"); 
} 

public static Class<?> getClassFromPath(String path) { 
    try { 
     File file = new File(path); 
     URL[] urls = {new URL(path)}; 
     URLClassLoader cl = URLClassLoader.newInstance(urls); 
     if (!file.isDirectory() && file.getName().endsWith(".class")) { 
      String className = file.getName().substring(0, file.getName().length() - 6); 
      className = className.replace('/', '.'); 
      Class c = cl.loadClass(className); 
      return c; 
     } 
     for (File f : file.listFiles()) { 
      if (f.isDirectory() || !f.getName().endsWith(".class")) { 
       continue; 
      } 
      String className = f.getName().substring(0, f.getName().length() - 6); 
      className = className.replace('/', '.'); 
      Class c = cl.loadClass(className); 
      return c; 
     } 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 
} 
+0

感谢您解决这个问题...我似乎有问题张贴代码... – JNorr44 2013-04-07 01:16:34

回答

3

我敢肯定,你可以尝试这样的事:

InputStream stream = clazz.getClassLoader().getResourceAsStream(classAsPath); 

其中classAsPath是你实际上在做你的方法是什么getClassFromPath

那么你可能想使用Apache的commons-io的读入的InputStream使用类似IOUtils.toByteArray一个byte []()

+2

+1这是正确的做法。但是您确实需要将类FQN映射到相应的路径名。 – 2013-04-07 02:31:24

+0

@Stephen C你完全正确 – 2013-04-07 02:57:16