Java Class ClassLoader

5934 단어 ClassLoaderClass
오후 에 '자바 깊이 모험' 을 보고 있 습 니 다. Class & ClassLoader 에 대한 포 지 셔 닝 이 명확 하지 않 아서 다음 블 로그 를 찾 았 습 니 다.
http://www.cnblogs.com/pony/archive/2008/10/10/1307921.html
   blog_name: 자바 동적 로드 클래스  코드 를 조금 만 수정 하면 달 릴 수 있다.ok,now show code:
총 4 개의 class -
package com.mark.core.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;

public class MyClassLoader extends ClassLoader {
    //      (Hashtable)     ,           。
    Hashtable loadedClasses;

    public MyClassLoader() {
        loadedClasses = new Hashtable();
    }

    @Override
    public synchronized Class loadClass(String className, boolean resolve) throws ClassNotFoundException {
        Class newClass;
        byte[] classData;

        //                      。
        newClass = (Class) loadedClasses.get(className);
        //           resolve  true,    。
        if (newClass != null) {
            if (resolve) {
                resolveClass(newClass);
            }
            return newClass;
        }

        /*
         *                                  。          ,                        ,                                  ,
         *  java.lang.System    ,                          ,                                。
         */

        try {
            newClass = findSystemClass(className);
            return newClass;
        } catch (ClassNotFoundException e) {
            System.out.println(className + " is not a system class!");
        }

        //        ,          URL     。
        try {
            //            ,       classData 。
            classData = getClassData(className);
            //                class     。
           // newClass = defineClass(classData, 0, classData.length);
            newClass = defineClass(null, classData, 0, classData.length);
            if (newClass == null) {
                throw new ClassNotFoundException(className);
            }
        } catch (Exception e) {
            throw new ClassNotFoundException(className);
        }

        //         ,            ,      。
        loadedClasses.put(className, newClass);
        //   resolve  true,      。
        if (resolve) {
            resolveClass(newClass);
        }
        return newClass;
    }

    //              。
    protected byte[] getClassData(String className) throws IOException {
        byte[] data;
        int length;
        try {
            //       URL        URL       。
            URL url = new URL(className.endsWith(".class") ? className : className + ".class");
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            length = connection.getContentLength();

            data = new byte[length];
            inputStream.read(data);
            inputStream.close();
            return data;
        } catch (Exception e) {
            System.out.println("================start:");
            e.printStackTrace();
            System.out.println("================end:");
            throw new IOException(className);
        }
    }
}

  interface:
 
package com.mark.core.test;

public interface Share {
    public void start(String[] option);
}

 
client test class:
 
package com.mark.core.test;

public class TestClassLoader {
    public static void main(String[] args) {
        MyClassLoader ll = new MyClassLoader();
        Class cc;
        Object oo;
        String ss = "http://localhost:8080/webdemo2/classes/RemoteClass.class";

        if (args.length != 0) {
            ss = args[0];
        }
        try {
            System.out.println("Loading class " + ss + "...");
            //        loadClass()     。
            cc = ll.loadClass(ss);
            System.out.println("Creat instance...");
            //   Object      。
            oo = cc.newInstance();
            System.out.println("Call start() method...");
            //                  。
            ((Share) oo).start(args);
        } catch (Exception e) {
            System.out.println("Caught exception : " + e);
            e.printStackTrace();
        }
    }
}

 
the file below should be deploy in server after compiler it.
package com.mark.core.test;


public class RemoteClass implements Share {

    /* (non-Javadoc)
     * @see com.mark.core.test.Share#start(java.lang.String[])
     */
    @Override
    public void start(String[] option) {
        System.out.println("congratulations!");
    }

}

 
how to?
step 1: build a java application project [A]. add the code above.
step 2: build a java_server project [B] that it can run on tomcat or other servers.
step 3: in java_server project : then you can  copy RemoteClass.class from project A to project B And don't forget to delete the RemoteClass.java in Project A.
step 4:
   update code.
 
String ss = "http://localhost:8080/webdemo2/classes/RemoteClass.class";

 

좋은 웹페이지 즐겨찾기