Java ClassLoader 加载class文件

先编译java文件成class文件
javac HelloC.java

package test;


public class HelloC {

    public static void main(String[] args) {
        System.out.println("test main");
    }

    public void test(){
        System.out.println("testddt ");
    }
}
加载class文件

public class Hello {

    public static void main(String[] args) throws Exception {
        //类加载
        byte[] clazzByte = loadClass();
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        Method method = Class.forName("java.lang.ClassLoader").getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
        method.setAccessible(true);
        Class clazz = (Class) method.invoke(classLoader, clazzByte, 0, clazzByte.length);

        //类链接
        method = Class.forName("java.lang.ClassLoader")
                .getDeclaredMethod("resolveClass", Class.class);
        method.setAccessible(true);
        method.invoke(classLoader,clazz);

        Method testM = clazz.getDeclaredMethod("test");
        testM.setAccessible(true);
        testM.invoke(clazz.newInstance());
    }


    public static byte[] loadClass() throws Exception {
        String path = "C:\\Users\\HelloC.class";
        FileInputStream in = new FileInputStream(path);
        long fileSize = new File(path).length();
        byte[] clazzSize = new byte[(int) fileSize];
        in.read(clazzSize);
        return clazzSize;
    }

你可能感兴趣的:(java,大数据)