0

My question is how to get an instance of java.lang.Class from a given .class file? So if I have the file MyClass.class, and the corresponding java.io.File instance, how can I use this to get an instance of java.lang.Class that corresponds to MyClass?

Marcus Mathioudakis
  • 837
  • 1
  • 6
  • 19

2 Answers2

0

Class<?> clazz = new URLClassLoader(new File("").toURL()).loadClass(className);

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

You actually need a classloader to do this (to turn a byte-code byte-stream into a class). There a few options here. One, you use a standard URLClassLoader instance, but that would rely on your being placed in a good java package location (you would create the URLClassLoader to the root of your file path in which you file resides. But this would only work when the directory structure mirrors the package structure of the class file you are trying to load).

The easiest base class would be SecureClassLoader as that allows you to run your code in a JVM with a security manager enabled (iow, you can set the code base)

The important method for you is the findClass as that would turn a binary name into a class (you can make your own mapping between the classname and the file your are loading). You can load the File and pass the bytes of the file to the most important method: defineClass. This is a method of the SecureClassLoader. It takes a binary name of your class, the ByteBuffer and a CodeSource (for Java Security)

To create a buffer from your file use:

FileInputStream fis = new FileInputStream(yourFileObj)
FileChannel channel = fis.getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, clsFile.length());

You need a CodeSource so you can use it in a secure environment, you might want to use something like:

CodeSource cs = new CodeSource(clsFile.getParent().toURI().toURL(), (CodeSigner[]) null);

and then invoke the

Class<?> aClass = super.defineClass(name, buffer, cs);

Hope this puts you into the right direction(!)

raphaëλ
  • 6,393
  • 2
  • 29
  • 35