JavaFileObject, how to supply byteCode byte array?

I have searched for a long time how to do a JavaFileObject which stores class byteCode. It does seem many people have related posting and understand how it works.

see for example, this posting

my question is the class MemoryJavaFileObject

the method
public OutputStream openOutputStream() {
      return out;
simply returns an OutputStream, which was initialized as a blank ByteArrayOutputStream.

The question is where and how does "out" ever get a byte array to make an output stream from.

another examples has

final class JavaFileObjectImpl extends SimpleJavaFileObject {
   // If kind == CLASS, this stores byte code from openOutputStream
   private ByteArrayOutputStream byteCode;

   // if kind == SOURCE, this contains the source text
   private final CharSequence source;

   JavaFileObjectImpl(final String baseName, final CharSequence source) {
      super(CharSequenceCompiler.toURI(baseName + CharSequenceCompiler.JAVA_EXTENSION),
      this.source = source;

    * Construct a new instance
    * @param name
    *           the file name
    * @param kind
    *           the kind of file
   JavaFileObjectImpl(final String name, final Kind kind) {
      super(CharSequenceCompiler.toURI(name), kind);
      source = null;

   public CharSequence getCharContent(final boolean ignoreEncodingErrors)
         throws UnsupportedOperationException {
      if (source == null)
         throw new UnsupportedOperationException("getCharContent()");
      return source;

   public InputStream openInputStream() {
      return new ByteArrayInputStream(getByteCode());

   public OutputStream openOutputStream() {
      byteCode = new ByteArrayOutputStream();
      return byteCode;

It is easy to see how it gets source content when it is a source file object. but for class code object, I don't see any way to direct the byteCode OutputStream to any real byte array.

Any body make sense of this? please help.
Who is Participating?
bhomassAuthor Commented:
never mind.

the way to write in the bytecode is to use the OutputStream provided by openOutputStream() method. just use the write method.
Can you read the class file into an array?
bhomassAuthor Commented:
the class file is already in a byte array format. the question is how to make a JavaFileObject out of it. After that I am good.
bhomassAuthor Commented:
I figured out by experimenting with code.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.