zoukankan      html  css  js  c++  java
  • 自定义Cass loader

    1、先建一个被加载的测试类

    public class Person {
    
        private Integer age;
    
        public Integer getAge() {
            return age;
        }
    
        @Override
        public String toString() {
            return "测试类加载成功";
        }
    }
    

      

    2、建一个自定义的类加载器

    继承ClassLoader类,重写findClass,这样不破坏Java的双亲委派机制。

        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;
            }
        }
    

      

    3、测试类

        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());
    
        }
    

      

    4、结果会输出 测试类加载成功

  • 相关阅读:
    安卓界面基本组件------计时器
    安卓界面组件----时间日期拾取器
    安卓界面组件----列表视图
    安卓组件------列表选择框
    Redis 开启远程访问
    收集的一个关于大批量插入数据的代码
    Server.MapPath和Request.PhysicalApplicationPath的异同
    C#中使用正则表达式验证电话号码、手机号、身份证号、数字和邮编
    cocos2d-x3.2在xcode6.1下的 环境搭建
    STL源码剖析(适配器)
  • 原文地址:https://www.cnblogs.com/fillPv/p/11175700.html
Copyright © 2011-2022 走看看