美文网首页
启动类总结

启动类总结

作者: lixwcqs | 来源:发表于2019-03-01 00:20 被阅读0次

    先看一个例子

    package com.cqs.learning.jvm;
    
    import jdk.nashorn.tools.Shell;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    /**
     * @author lixiaowen
     * @create 19-2-28
     */
    public class ClassLoaderDemo {
    
        public static void main(String[] args) {
    
            // bootstrap class loader example &&
            System.out.println(Object.class  + " classloader: "+ Object.class.getClassLoader());
    
            //ext class loader example
            //System.out.println(System.getProperty("java.ext.dirs"));
            System.out.println(Shell.class + " classloader: " + Shell.class.getClassLoader());
    
            //App class loader example
            System.out.println(ClassLoaderDemo.class + " classloader: " + ClassLoaderDemo.class.getClassLoader());
    
            // self define class loader example
            SelfDefineClassLoader selfDefineClassLoader = new SelfDefineClassLoader();
            try {
                //指定自定义加载器
                Class<?> aClass = selfDefineClassLoader.loadClass("com.cqs.learning.jvm.ClassLoaderDemo");
                Object o = aClass.newInstance();
                System.out.println(o.getClass() +"\t classloader: " + o.getClass().getClassLoader());
                //System.out.println(o instanceof com.cqs.learning.jvm.ClassLoaderDemo);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    
       static class SelfDefineClassLoader extends ClassLoader{
    
           @Override
           public Class<?> loadClass(String name) throws ClassNotFoundException {
               String fileName = name.substring(name.lastIndexOf(".")+1) + ".class";
               InputStream is = getClass().getResourceAsStream(fileName);
               if (is == null){
                   return super.loadClass(name);
               }
               try {
                   byte[] bytes = new byte[is.available()];
                   is.read(bytes);
                   return defineClass(name,bytes,0, bytes.length);
               } catch (IOException e) {
                   throw new RuntimeException();
               }
           }
       }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:启动类总结

          本文链接:https://www.haomeiwen.com/subject/dwtruqtx.html