Guest User

Untitled

a guest
May 21st, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import java.io.*;
  2.  
  3. public class FileSystemClassLoader extends ClassLoader {
  4.  
  5. private String rootDir;
  6.  
  7. public FileSystemClassLoader(String rootDir) {
  8. this.rootDir = rootDir;
  9. }
  10.  
  11. protected Class<?> findClass(String name) throws ClassNotFoundException {
  12. byte[] classData = getClassData(name);
  13. if (classData == null) {
  14. throw new ClassNotFoundException();
  15. }
  16. else {
  17. return defineClass(name, classData, 0, classData.length);
  18. }
  19. }
  20.  
  21. private byte[] getClassData(String className) {
  22. String path = classNameToPath(className);
  23. InputStream ins = null;
  24. ByteArrayOutputStream baos = null;
  25. try {
  26. ins = new FileInputStream(path);
  27. baos = new ByteArrayOutputStream();
  28. int bufferSize = 4096;
  29. byte[] buffer = new byte[bufferSize];
  30. int bytesNumRead = 0;
  31. while ((bytesNumRead = ins.read(buffer)) != -1) {
  32. baos.write(buffer, 0, bytesNumRead);
  33. }
  34. return baos.toByteArray();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. } finally
  38. {
  39. closeIO(ins);
  40. closeIO(baos);
  41. }
  42. return null;
  43. }
  44.  
  45. private void closeIO(Closeable closeable)
  46. {
  47. if (closeable == null) return;
  48. try
  49. {
  50. closeable.close();
  51. } catch (IOException e)
  52. {
  53. e.printStackTrace();
  54. }
  55. }
  56.  
  57. private String classNameToPath(String className) {
  58. return rootDir + File.separatorChar
  59. + className.replace('.', File.separatorChar) + ".class";
  60. }
  61. }
Add Comment
Please, Sign In to add comment