类的加载(加载.class文件或者jar包中的类)

加载.class文件方式
public class MyClassLoader extends ClassLoader{

protected Class findClass(String dir) throws ClassNotFoundException {
    File classFile = new File(dir);
    if(!classFile.exists()){
        throw new ClassNotFoundException(classFile.getPath() + " 不存在") ;
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    ByteBuffer bf = ByteBuffer.allocate(1024) ;
    FileInputStream fis = null ;
    FileChannel fc = null ;
    try {
        fis = new FileInputStream(classFile) ;
        fc = fis.getChannel() ;
        while(fc.read(bf) > 0){
            bf.flip() ;
            bos.write(bf.array(),0 , bf.limit()) ;
            bf.clear() ;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            fis.close() ;
            fc.close() ;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return defineClass(bos.toByteArray() , 0 , bos.toByteArray().length);
 }
}

=======================================================

       public class Test {
          public static void main(String[] args) throws 
           ClassNotFoundException{
         int i = 0 ;
       System.out.println("开始了");
           while(true){
           MyClassLoader mcl = new MyClassLoader() ;
          System.out.println(mcl.getParent());
         Class personClass =  
          mcl.findClass("D:\\workspace\\test.class");
       try {
           Object person =  personClass.newInstance() ;

           Method sayHelloMethod = personClass.getMethod("say") ;
           sayHelloMethod.invoke(person) ;
           System.out.println(++i);

       } catch (Exception e) {
           e.printStackTrace();
       }
       try {
           Thread.sleep(3000) ;
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
   }
 }
加载jar包的方式
public static void main(String[] args) throws Exception{
    File file = new File("D:/workspace/mysql-connector-java-6.0.5.jar");
    URLClassLoader loader = new URLClassLoader(new URL[]{ file.toURI().toURL() });
    Class clazz = loader.loadClass("com.mysql.cj.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    Properties p = new Properties();
    p.put("user", "root");
    p.put("password", "root123");
    Connection conn = 
    driver.connect("jdbc:mysql://192.168.*.10:3306/test?
    useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true
   &useLegacyDatetimeCode=false&serverTimezone=UTC",p);
    System.out.print(conn.toString());
}

你可能感兴趣的:(类的加载(加载.class文件或者jar包中的类))