Implement Java Dynamic class loading mechanism

Source: Internet
Author: User

This is the best example for loading the data into the machine using the dynamic class of Java, for the web browser root with Java expansion, please load the Java Applet from the dynamic state in the network or local file system (following the rules of Java small application program class ), then it will be executed in the local system, greatly increasing the Main Page's power.

---- Actually, Java itself is an extremely dynamic language. Similar to the dynamic link library (DLL) of windows, Java should be compiled into a class file with a single character, when running the SQL statement, the root data must be loaded into the corresponding class by the dynamic state of the Java Virtual Machine. This machine makes it possible to compile and write the dynamic distribution type in the Process Order: We can compile and write our own class loaders on the customer end, however, the scripts that are executed are stored on the local host, local network, or another host in the world. The following describes how Java's dynamic class is loaded into the machine system in the application sequence.

The system class that is connected with the dynamic class.

---- For supporting dynamic class loading, two classes are provided in the system class group java. LANG: Class class and classloader class.

---- 1. java. Lang. Class. In Java virtual machines, each class or interface is operated vertically by the class, and it cannot be explicitly instantiated, the object of the class must be obtained using its other method. How can I obtain the class-type object of a class when the key of the dynamic class is loaded into the machine. The correlation method mainly includes:

---- Public static class forname (string classname)

---- This is a static method. It obtains the Class Object of the class with the specified name. The class name can be like "Sun. applet. applet ", but it cannot contain information such as path paths or network addresses. This is the most convenient way to load classes from the dynamic state in the local system.

---- Public object newinstance ()

---- This is the most important method. It establishes an instance of the specified class as described in the class type.

---- The bottom is a code generated by using the forname () and newinstance () method to implement the dynamic class. The share class package contains an interface, the detailed content will be explained in Part 3.

Try {

// Create a class object based on the class name.

Class cc = Class. forname ("Class Name "));

// Create an instance of the loaded class and force type conversion,

The value is assigned to the share type variable.

Share oo = (SHARE) CC). newinstance ();

// Call the method of this class for work.

}

Catch (exception ex ){

// If exceptions occur, process them accordingly.

};

---- 2. Class java. Lang. classloader. This is an image extraction class. If you use it for computation, you must inherit it and rewrite its loadclass () method. Its main methods include:

---- Protected classloader ();

---- This is a constructor. You can use it to create a classloader class instance. Note that the class that inherits this class must rewrite this method, and cannot use the constructor of the province.

---- Protected abstract class loadclass (string name, Boolean resolve)

---- Load the specified class data, establish the Class Object and analyze it according to the data. This is an image extraction method, and everyone must re-write this method in their own sub-classes, the re-writing rule can take the example of the third part of the examination.

---- Protected final class defineclass (byte data [], int offset, int length)

---- Define the data in the number group as a Class Object. The format of the number group is determined by the virtual computer.

---- Protected final class findsystemclass (string name)

---- The root data is loaded into the class according to the specified class name. It will automatically search for the class in the path specified by "classpath" and the Environment Change volume, if the classnotfoundexception is not found.

---- Protected final void resolveclass (Class C)

---- Analyzes this class by means of the classes related to the specified class, which must be completed before the class is used.

Added the classllader class to load

---- The best way to solve the dynamic loading mechanism is through the example child. The following example child is composed of four classes, the following is an explanation:

---- 1. The myclassloader class is a sub-class of the classloader class. It rewrites the loadclass method and loads the class dynamic state specified by the URL address on the network, obtain the power of its class object. The reader can write the code of the lower layer based on the specific method of the Self-loaded class.

Import java. Io .*;

Import java. util .*;

Import java.net .*;

Public class myclassloader extends classloader {

// Defines the hashtable variable,

Used to save the loaded class data.

Hashtable loadedclasses;

Public myclassloader (){

Loadedclasses = new hashtable ();

}

Public synchronized class loadclass (string classname,

Boolean resolve) throws classnotfoundexception {

Class newclass;

Byte [] classdata;

// Check whether the class data to be loaded has been saved in the hash table.

Newclass = (class) loadedclasses. Get (classname );

// If the class data already exists and the resolve value is true, parse it.

If (newclass! = NULL ){

If (RESOLVE)

Resolveclass (newclass );

Return newclass;

}

----/* First try to attach the specified class from the local system class group. This is required, because after the VM loads this class, what other classes are used for analyzing and executing it, such as Java. lang. the system class will no longer use the class loader of the virtual pseudo-machine, but will call the self-built Class Loader for loading. */

Try {

Newclass = findsystemclass (classname );

Return newclass;

} Catch (classnotfoundexception e ){

System. Out. println (classname + "is not a system class! ");

}

// if it is not a system class,
try to load the class from the URL address specified in the network.
try {
// use a custom method to load class data.
the data is stored in the byte array classdata.
classdata = getclassdata (classname);
// create a class object based on the data contained in the byte array.
newclass = defineclass (classdata, 0, classdata. length);
If (newclass = NULL)
throw new classnotfoundexception (classname );

}catch (exception e) {
throw new classnotfoundexception (classname);

}

// If the class is correctly loaded,

Save the class data in the hash table for reuse.

Loadedclasses. Put (classname, newclass );

// If the resolve value is true, the class data is parsed.

If (RESOLVE ){

Resolveclass (newclass );

}

Return newclass;

}

// This method loads class data from the network.

Protected byte [] getclassdata (string classname)

Throws ioexception {

Byte [] data;

Int length;

Try {

// Use the URL class method from the network

Load the data of the class of the specified URL address.

URL url = new URL (classname. endswith (". Class ")?

Classname: classname + ". Class ");

Urlconnection connection = URL. openconnection ();

Inputstream = connection. getinputstream ();

Length = connection. getcontentlength ();

Data = new byte [length];

Inputstream. Read (data );

Inputstream. Close ();

Return data;

} Catch (exception e ){

Throw new ioexception (classname );

}

}

}

---- 2. Since Java is a strong class-type query language, the class loaded through the network is only an object-type object after being instantiated, virtual machines do not know which method should they begin to execute when they include such methods. Because of this, classes that can be loaded in the dynamic state must inherit a certain image class or implement a certain interface, because only one of the parent classes can be used, the specific interface is usually used. The lower Code defines a socket class share and its method start ().

Public interface share {

Public void start (string [] Option );

}

---- 3. The testclassloader class uses the loadclass () method of the myclassloader class to load the class with a specified URL address and execute it in the local system, implements the dynamic loading of the class. Note that the forced data type should be converted to another type before the method of carrying the row into the class.

Public class testclassloader {

Public static void main (string [] ARGs ){

Myclassloader LL = new myclassloader ();

Class cc;

Object Oo;

String Ss ="Http://kyzser.ydxx/classLoader/Tested.class";

If (ARGs. length! = 0) Ss = ARGs [0];

Try {

System. Out. println ("loading class" + SS + "...");

// Use the override method loadclass () to load class data.

Cc = ll. loadclass (SS );

System. Out. println ("creat instance ...");

// Create an object-type class instance.

OO = cc. newinstance ();

System. Out. println ("Call start () method ...");

// Force type conversion and execute the method in the loaded class.

(SHARE) Oo). Start (ARGs );

} Catch (exception e ){

System. Out. println ("caught exception:" + E );

}

}

}

---- 4. The tested class is simple and can be placed on any web server, but it should be noted that it can be loaded in and executed in dynamic mode, first, implement the method in the pre-defined interface. The following example shows the start method of port share.

Public class tested implements share {

Public void start (string [] Option ){

// EnterProgramCode.

}

}

The entry points of the dynamic Class System

---- 1. The distribution method should be used. This is the most useful method for the customer end of the long journey, the customer only needs to install a basic system and a class capable of real-time dynamic loading, when the local system is not stored in the power, only the Network Dynamic State must be loaded and the corresponding class should be executed. Because the most recent version of software is used by the client, the upgrade and maintenance questions of software are no longer stored, that is, the so-called "Zero management" model is implemented.

---- 2. Password The. Class file. The bytecode in Java is easy to be reversed and translated, big departments are concerned about their own achievements and won by others. In this case, you can perform the encryption processing for the Classware, and use the self-contained classloader to perform the corresponding decryption when executing the code, you can solve this question.

---- 3. Make the third-party initiator easy to expand your application. It can be seen from the front that all classes can be loaded and executed by your class loader in the dynamic state, it is necessary to inherit the class you define or implement the interface you define. In this case, you can define some rules, so that the attacker will not be able to solve your application in the process sequence, but also to expand the power.

---- However, there must be advantages and disadvantages. in the network, the active nodes loaded with dynamic classes should be lacking in security, it is difficult to prove that it is not carried into the undesirable code generation. This question depends on the Java security manager and the appropriate encryption algorithm, beyond the discussion in this article.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.