Saturday, July 24, 2010

how to create a Java class object from a file


public static Class createClassFromBytes(String fileName) {
  Class clazz = null;
  File file = new File(fileName);
  try {
   byte[] ba = getBytesFromFile(file);
   // FileVisitor extends ClassLoader
   clazz = new FileVisitor().defineClass(null, ba, 0,

   (int) file.length());
  } catch (IOException e) {
   e.printStackTrace();
  }
  return clazz;
 }

 public static byte[] getBytesFromFile(File file) throws IOException {
   InputStream is = null;
   try {
    is = new FileInputStream(file);
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }
   byte[] bytes = new byte[(int) file.length()];
   // Read in the bytes
   int offset = 0;
   int numRead = 0;
   try {
    while (offset bytes.length (numRead = is.read(bytes, offset, bytes.length - offset)) = 0) {
     offset += numRead;
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
   // Ensure all the bytes have been read in
   if (offset < bytes.length) {
    throw new IOException("Could not completely read file "
      + file.getName());
   }
   // Close the input stream and return bytes
   is.close();
   return bytes;
  }


syntax highlighted by Code2HTML, v. 0.9.1


0 comments: