public Class loadNewClass(String javaFile, String packageName) { Class myClass = null; String className = javaFile.replace(".java", ".class"); File inpFile = new File(className); int idx = className.lastIndexOf(File.separatorChar); String javaName = className.substring(idx + 1, className.indexOf(".")); int size = (int) inpFile.length(); byte[] ba = new byte[size]; try { FileInputStream fis = new FileInputStream(className); // read the entry int bytes_read = 0; while (bytes_read != size) { int r = fis.read(ba, bytes_read, size - bytes_read); if (r < 0) break; bytes_read += r; } if (bytes_read != size) throw new IOException("cannot read entry"); } catch (FileNotFoundException fnfExc) { System.out.println("File : " + className + " not found"); fnfExc.printStackTrace(); } catch (IOException ioExc) { System.out.println("IO Exception in JavaCompile trying to read class: "); ioExc.printStackTrace(); } try { String packageAppendedFileName = ""; if (packageName.isEmpty()) packageAppendedFileName = javaName; else packageAppendedFileName = packageName + "." + javaName; packageAppendedFileName.replace(File.separatorChar, '.'); myClass = defineClass(packageAppendedFileName, ba, 0, size); // SOS-StergAutoCompletionScalaSci.upDateAutoCompletion(myClass); String userClassName = myClass.getName(); JOptionPane.showMessageDialog(null, "Class " + userClassName + " loaded successfully !"); } catch (ClassFormatError exc) { System.out.println("error defining class " + inpFile); exc.printStackTrace(); } catch (Exception ex) { System.out.println("some error defining class " + inpFile); ex.printStackTrace(); } return myClass; }
protected byte[] getClassData(String directory, String name) { String classFile = directory + "/" + name.replace('.', '/') + ".class"; int classSize = (int) new File(classFile).length(); byte[] buf = new byte[classSize]; try { FileInputStream filein = new FileInputStream(classFile); classSize = filein.read(buf); filein.close(); } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } return buf; }