[JAVA] Loading classes from Path

Overview

Load the class file indicated by Path.

code

ClassLoaderFromPath.java


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class ClassLoaderFromPath extends ClassLoader{
    private final ClassLoader parent;
    public ClassLoaderFromPath(ClassLoader parent) {
        super(parent);
        this.parent = parent;
    }

    public Class loadClassFile(Path path) throws IOException{
        byte[] data = Files.readAllBytes(path);
        return defineClass(null,data,0,data.length);
    }
}

2017/01/14-20:35

Fixed because static initializer is not called if the above is left as it is

ClassLoaderFromPath.java


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class ClassLoaderFromPath extends ClassLoader{
    private final ClassLoader parent;
    public ClassLoaderFromPath(ClassLoader parent) {
        super(parent);
        this.parent = parent;
    }

    public Class loadClassFile(Path path) throws IOException,ClassNotFoundException{
        byte[] data = Files.readAllBytes(path);
        return Class.forName(defineClass(null,data,0,data.length).getName());
    }
}

Recommended Posts

Loading classes from Path
Create path from array
Java, abstract classes starting from beginners
Choose a class hierarchy from tagged classes