Custom loader

Custom class loader

1, the class loader is capable of loading into the JVM .class, loaded into the object class of the object, is responsible for reading Java byte code, and converted into an instance of class java.lang.Class class loader kinds, It needs to be loaded.
2, the class loader loading:
  1) loading implicitly Student stu = new Student (), using the native JDK class loader;
  2) by Class.forName ( "com.javaee.Student"); ( JDBC connector similar databases).
  3) can be loaded from the suffix defined class, guarantee to get the server being attacked file is not available, play a role in protection.
3, used for servers, remote processing.
Example:

public class Demo01 {
    public static void main(String[] args) throws Exception{
        MessageClassLoader messageClassLoader = new MessageClassLoader();
        String kindName = "com.tx.test.classloader.Message";
        Class<?> clazz = messageClassLoader.loadData(kindName);
        Object object = clazz.getDeclaredConstructor().newInstance();
        Method method = object.getClass().getDeclaredMethod("print",String.class);
        method.invoke(object,"www.baidu.com");
    }
}
//自定义类加载器
class MessageClassLoader extends ClassLoader {

    public Class<?> loadData(String kindName) {
        String addressName = "E:" + File.separator + "IDEA_JavaSE练习" + File.separator + "类加载器"
                + File.separator + "src" + File.separator + kindName.replace(".", File.separator) + ".class";
        try {
            InputStream in = new FileInputStream(new File(addressName));
            int len = in.available();
            byte[] data = new byte[len];
            int read = in.read(data, 0, len);
            return this.defineClass(kindName, data, 0, len);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}



result:

send Show:www.baidu.com
Published 61 original articles · won praise 0 · Views 2171

Guess you like

Origin blog.csdn.net/sabstarb/article/details/104403301