1

I have tried the following code, and got an exception. Can someone help me with this,

package defineClass;

import java.io.FileInputStream;
import java.io.IOException;

public class DefineClass extends ClassLoader {

    static String PATH = "E:\\WorkSpaceOpkey\\tester\\src\\test2\\Bar.java";

    public static void main(String[] m) throws IOException {
        FileInputStream fis = new FileInputStream(PATH);
        byte[] b = new byte[fis.available()];
        fis.read(b);
        new DefineClass().defineClass("test2.Bar", b, 0, b.length);
    }

}

i am getting following error in defining class

Exception in thread "main" java.lang.ClassFormatError: Incompatible magic 
value 1885430635 in class file test2/Bar
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at defineClass.DefineClass.main(DefineClass.java:14)
Nipuna Priyamal
  • 370
  • 2
  • 14

1 Answers1

2

Simply not possible, as class loaders load compiled classes:

Converts an array of bytes into an instance of class Class,

You can't use a ClassLoader to load a java source code file.

If you want to dynamically use java source code, you will have to compile that source code into bytecode first, see here for options how to do that.

The real answer of course: don't just assume what classes do. Always read their corresponding java doc, and do more research. There are many good resources that explain class loaders in detail, like here.

GhostCat
  • 137,827
  • 25
  • 176
  • 248