Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8941781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T11:22:42+00:00 2026-06-15T11:22:42+00:00

I have a program that writes a string to a .java file, uses javax.tools

  • 0

I have a program that writes a string to a .java file, uses javax.tools to compile that .java file into a .class file, and I then use a modified ClassLoader to attempt to get a Runnable instance of the class (by turning it into a byte array and using ClassLoader.defineClass to get an instance). But.., I’m having a problem. When the program attempts to get an instance of the class, it notices that it was not compiled the right way. I get a ClassFormatError that reads Incompatible magic value 1885430635 in class file <Unknown>. Here is my (fairly sloppy, at the moment) code:

import java.io.*;
import java.security.SecureClassLoader;

public class EnhancedClassLoader extends SecureClassLoader
{
    public Object createObjectFromFile(String fileName) throws 
    InstantiationException, IOException, IllegalAccessException
    {
        File file = new File(fileName);
        definePackage("compClassPack", null, null, null, null, null, null, file.toURI().toURL());
        byte[] classBytes = null;
        //ReadFileToByteArray
        {
            FileInputStream fis = new FileInputStream(file);
            int size = (int)file.length();
            classBytes = new byte[size];
            int offset = 0;
            int readed;
            while (offset < size && (readed = fis.read(classBytes, offset, size - offset)) != -1)
            {
                offset += readed;
            }
        fis.close();
        }
        Class<?> clazz = defineClass(null, classBytes, 0, classBytes.length);
            //The error is thrown here! ^^^

        return clazz.newInstance();
    }
}

.

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

public class Main
{
    public static void main(String[] args)throws Exception
    {
        File file = new File("Sample.java");
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);

        String code =
                "package compClassPack;\n" +
                "public class Sample implements Runnable\n" +
                "{\n" +
                "    public Sample(){}\n\n" +
                "    public static void main(String[] args)\n" +
                "    {\n" +
                "        new Sample().run();\n" +
                "    }\n\n" +
                "    public void run()\n" +
                "    {\n" +
                "        System.out.println(\"It worked! :D\");\n" +
                "    }\n" +
                "}";

        for(byte ch : code.getBytes())
        {
            if((char)ch!='\n')
                bw.write((char)ch);
            else
                bw.newLine();
        }
        bw.flush();
        bw.close();

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
        JavaCompiler.CompilationTask ct = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
        ct.call();

        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics())
            System.out.format("Error on line %d in %d%n",
                    diagnostic.getLineNumber(),
                    ((FileObject)diagnostic.getSource()).toUri());

        fileManager.close();

        EnhancedClassLoader loader = new EnhancedClassLoader();
        Runnable runs = (Runnable) loader.createObjectFromFile(file.getAbsolutePath());
        runs.run(); 
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T11:22:42+00:00Added an answer on June 15, 2026 at 11:22 am

    Your byte array is not valid bytecode. If it were, it would begin with the magic string (hex) 0xCAFEBABE. Instead, your first bytes are 1885430635 (decimal), which is hex 0x7061636b, which read one byte at a time gives the ASCII characters pack, which is just the beginning of the package declaration.

    In other words, you are trying to load a text file as if it were bytecode, and obviously Java can’t construct any class from such a byte stream.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple Java program that takes a .jrxml file, compiles it, then
I have a program where I compile java code that somebody writes in a
I have a program that has to encrypt an audio file and then decrypt
I have a Java program that reads some text from a file, line by
I have a Java program that runs on Linux and telnets into a remote
I have here a program that enters a paragraph and writes it into a
I have a program with Driver GUI java file that creates a JFrame and
I have this java program where I transform with TransformerFactory a XML string that
I have a C++ program that writes to stdout that I am trying to
I have to write a Java program that tells what coins to give out

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.