自定義Cass loader

一、先建一個被加載的測試類java

public class Person {

    private Integer age;

    public Integer getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "測試類加載成功";
    }
}

  

二、建一個自定義的類加載器api

繼承ClassLoader類,重寫findClass,這樣不破壞Java的雙親委派機制。ide

    public class PathClassLoader extends ClassLoader{
        private String classPath;

        public PathClassLoader(){

        }

        public void setClassPath(String classPath) {
            this.classPath = classPath;
        }

        @Override
        protected Class<?> findClass(String className) throws ClassNotFoundException {
            byte[] classData = getClassByte(className);
            if(classData == null){
                throw new ClassNotFoundException();
            }
            return defineClass(className,classData,0,classData.length);
        }

        public byte[] getClassByte(String className) {
            String path = classPath + File.separator+ className.replace(".",File.separator) + ".class";
            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(path);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length = 0;
                while ((length=inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer,0 ,length);
                }
                return byteArrayOutputStream.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

  

三、測試類測試

    public static void main(String[] args) throws Exception {
        String classPath = "D:\\workspace\\idea\\fmdes\\target\\classes";
        PathClassLoader classLoader = new PathClassLoader();
        classLoader.setClassPath(classPath);
        String className = "com.fmys.api.test.Person";
        Class loadClass = classLoader.loadClass(className);
        System.out.println(loadClass.newInstance());

    }

  

四、結果會輸出 測試類加載成功this

相關文章
相關標籤/搜索