Implementation of Java's dynamic type

zhaozj2021-02-08  470

As the best example of the Dynamic Loading Mechanism with Java, a web browser with Java extension is dynamically loaded Java Applet from the network or local file system (followed by a certain rule of Java mini), and then The local system is executed, which greatly enhances the functionality of the home page.

---- The Java is a very dynamic language. Similar Windows dynamic link library (DLL), Java application program is always compiled into a single-independent Class file, and the program is subject to the Java virtual machine to dynamically load the corresponding class. Such mechanisms make the pattern of the plotted dynamic score application to be available: I can write self-employed type loaders at the client, and the prime sequence that is truly executed is stored in the mainframe of the other end of the world, the local area. The next step will be introduced to realize the dynamic type of Java in its own procedure.

Targeted systemic class with dynamic class

---- To support dynamic type loading machine, two classes in Java.lang in the system class: Class and ClassLoader class.

---- 1, class java.lang.class. In the Java virtual machine, each class or interface is manifested by the Class class, which cannot be explicitly instantiated, and it is necessary to use other ways to get the Class class. The key to the dynamic type load enabled is one step in which the Class type of the class is obtained. The party must have:

---- Public Static Class Forname (String ClassName)

---- This is a static method. It obtains the class type object of the class of the name of the name, the class name can be a string like "sun.applet.applet", but it is not information such as a path or network address. This is the most convenient way of moving into classes from the local system.

---- Public Object NewInstance ()

---- This is the most important method, which establishes an example of the specified class described by the Class type object.

---- The lower surface is a code that uses forname () and newinstance () to real dynamic class. The Share class contains an interface, and the details will be interpreted in the third part.

Try {

/ / Establish a Class type object based on the class name.

Class CC = Class.Forname ("Class Name));

/ / Establish an instance of the subloaded class and enforce the type conversion,

The value is assigned to the variable of the Share type.

Share = ((share) cc) .newinstance ();

// Call the method of this class work.

}

Catch (Exception EX) {

// If an exception occurs, the corresponding processing is performed.

}

---- 2, class java.lang.classloader. This is an abstract class. If you think it is to use it, you must keep it and rewrite its loadClass () method. Its main needs: ---- protected classloader ();

---- This is a constraint that can be used to build a ClassLoader class. Note that the class must rewrite this method without using the default consociate.

---- Protected Abstract Class LoadClass (String Name, Boolean Resolve)

---- The specified class data is loaded, and the Class type pair is built and it is necessary to solve it. This is an abstract method, and the big family must rewrite this method in its own subclass, and the regulations rewritten can be taken into the example of the third part.

---- Protected Final Class DefineClass (Byte Data [], INT Offset, Int Length

---- Will the data in the byte array define the Class type object, the format of the byte array is specified by the virtual machine.

---- Protected Final Class FindsystemClass (String Name)

---- According to the specified class name, it will be self-moved in the path specified by the previous directory and the environmental variable "classpath". If you can't find it, you will throw out the ClassNotFoundException Example.

---- Protected Final Void ResolVeclass (Class C)

---- Configure this class through all classes associated with the specified class, which must be completed before the class is used.

Expressing the ClassLlader class with real-purpose

---- The best way to solve the genre-loaded machinery system is to pass the example, the entire example of this complete example is formed by four classes, and the separation is as follows:

---- 1, MyClassLoader class is a subclass of the ClassLoader class. It rewrites the LoadClass method. It realizes the ability to use the URL address specified by the URL address to obtain its Class type object. The reader can rewrite the code of the lower surface in accordance with the specific form of the self-contained class.

Import java.io. *;

Import java.util. *;

Import java.net. *;

Public class myclassloader extends classloader {

// Define the variable of the hashtable type.

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 if 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, it parsed it.

IF (newclass! = NULL) {

IF (resolve)

ResolVeclass (NewClass);

Return newclass;

}

---- / * First trial map from the local system class group into the specified class. This is a must, because the virtual machine will load this class, in parsing and executing any other classes used, such as java.lang.system class, etc., no longer use the virtual machine class loader, and It is called our homemade class loader to load. * /

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,

Then try to load classes from the URL address specified in the network.

Try {

// Load the class data with a custom method,

Store in byte arrays ClassData.

ClassData = getClassData (ClassName);

// Establish a Class type object by the data contained by 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 properly loaded,

The class data is saved 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 is loaded into class data from the network.

protected byte [] getClassData (String ClassName)

THROWS IOEXCEPTION {

Byte [] DATA;

Int length;

Try {

// Method for using URL class from the network

Load the data of the class that specifies the URL address.

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) {throw new oException (classname);

}

}

}

---- 2, by Java is a strong type of inspection language. After being instantiated after the network, it is just an object type object. The virtual machine does not know how to include those methods, which method should be implemented. Therefore, the class that can be dynamically loaded must be in a certain amount of abstract classes or a real-one interface, because there is only one of the parent classes, and the implementation of a specific interface is commonly used. The code of the lower surface defines a interface Share and its method Start ().

Public interface share {

Public void start (String [] Option;

}

---- 3, the TestClassLoader class will specify the class of the URL address in the TestClassLoader class, which will specify the type of URL address and implement it in the local system. Note It is necessary to perform it to force the data type conversion before the method of being loaded 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 rewritten method loadClass () to load the class data.

CC = ll.loadclass (ss);

System.out.Println ("Creat Instance ...");

// Create a class instance of the Object type.

OO = cc.newinstance ();

System.out.println ("Call Start () Method ...");

// Mandatory type conversion and execute the method in which it is loaded.

(Share) oo) .start (args);

} catch (exception e) {

System.out.println ("CAUGHT EXCEPTION: E);

}

}

}

---- 4, TESTED class is simple, can be placed on any Web server, but should not be able to dynamically load and executed classes, and set the method of pre-defined interface. The examples of the lower surface realize the START method of the interface.

Public class tsted imports share {

Public void start (String [] option) {

// Fill in the program code.

}

}

Some applications for dynamic types

---- 1, disconnecting distribution. This is the most useful for developing remote client applications. The client only needs to install some basic systems and a class that enables dynamic class load mechanisms. When the function does not exist, only needs to be dynamically loaded from the network. Perform a corresponding class to get a specific function. Due to the latest version of the software is the latest version of the software, the "zero management" model is now known as the upgrade and maintenance issues that are no longer stored. ---- 2, add your .class file. By the Java's word code (bytecode) is easy to be re-edited, the large-scale development of Java should be worried by others. It can solve this problem to solve this problem with the appropriate encryption processing of the type of document, and use the self-employed type loader.

---- 3, so that the third party developers are easy to expand your applications. As you can see, all classes that can be dynamically loaded and executed by your class loader, must inherit your defined classes or implement your defined interface, so you can develop some rules, so that other developers don't have to know you The application can also expand the function.

---- Of course, it is advantageous that the main defects that use dynamic load in the network are security, it is difficult to guarantee that there is no uncomfortable code, this problem depends on Java's security manager and appropriate The encryption algorithm is solved, which has exceeded the discussion scope of this article.

转载请注明原文地址:https://www.9cbs.com/read-909.html

New Post(0)