/*
** Module   : InMemoryClass.java
** Abstract : in-memory class file
**
** Copyright (c) 2009, Golden Code Development Corporation.
**
** -#- -I- --Date-- -----------------------Description------------------------
** 001 GES 20090302 Provides an in-memory class file.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.goldencode.compile;

import javax.tools.*;
import java.io.*;
import java.net.*;

/**
 * An in-memory representation of the Java byte code for a class. This
 * representation is sufficient to be an output destination of the Java
 * compiler, bypassing the file system completely.
 */
public class InMemoryClass
extends SimpleJavaFileObject
{
   /** Output destination which is an in-memory stream. */
   private ByteArrayOutputStream out = new ByteArrayOutputStream();
   
   /**
    * Construct an instance that represents the byte code for the given
    * class name and which can be written to as an output destination.
    *
    * @param    name
    *           Fully qualified class name (includes package and any inner
    *           class extensions) in proper Java Language Specification format
    *           WITHOUT any ".class" suffix.
    */
   public InMemoryClass(String name)
   {
      super(URI.create("string:///"                           +
                       name.replaceAll("\\.", File.separator) +
                       Kind.CLASS.extension),
                       Kind.CLASS);
   }
   
   /**
    * Obtain the byte code for this class.
    *
    * @return   The byte code.
    */
   public byte[] getBytes()
   {
      return out.toByteArray();
   }
   
   /**
    * Obtain a stream for the class file resource represented by this instance.
    *
    * @return   The byte array output stream that will contain the compiler
    *           output.
    */
   public OutputStream openOutputStream()
   {
      return out;
   }
}
