初探Java类加载机制_MySQL
一、在jdk1.2以后,类加载是通过委托来完成的,这意味着如果 ClassLoader 不能找到类,它会请求父代 ClassLoader 来执行此项任务,所有 ClassLoaders 的根是系统 ClassLoader,它会以缺省方式装入类 -- 即,从本地文件系统。今天我们就来探讨一下在jvm中这些机制是怎样运行的。让我们假设有一个class字节码文件(比如Hello.class文件),那么在应用程序中,他是如何被加载进来,并形成一个类对象的呢?我们这篇文章的目的就是为了解释这个问题。
在java.lang包里有个ClassLoader类,ClassLoader 的基本目标是对类的请求提供服务。当 JVM 需要使用类时,它根据名称向 ClassLoader 请求这个类,然后 ClassLoader 试图返回一个表示这个类的 Class 对象。通过覆盖对应于这个过程不同阶段的方法,可以创建定制的 ClassLoader。其中有个loadClass(String name, boolean resolve)方法,该方法为ClassLoader的入口点,在jdk1.2以后,loadClass方法将缺省调用findClass方法,详细内容可以参考API文档,我们编写的ClassLoader主要就是为了覆盖以上两个方法。回到我们刚才的问题,怎样读进字节码文件,并把它构成一个类对象呢?在ClassLoader里有个方法,Class defineClass(String name, byte[] b, int off, int len),答案就在这里了,我们根据把class字节码文件(如Hello.class)读进一个字节数组里,byte[] b,并把它转化为Class对象,而这些数据可以来源于文件,网络等,神奇吧:)
defineClass管理 JVM 的许多复杂、神秘和倚赖于实现的方面 -- 它把字节码分析成运行时数据结构、校验有效性等等。不必担心,您无需亲自编写它。事实上,即使您想要这么做也不能覆盖它,因为它已被标记成最终的。
其他一些方法:
findSystemClass方法:从本地文件系统装入文件。它在本地文件系统中寻找类文件,如果存在,就使用 defineClass 将原始字节转换成 Class 对象,以将该文件转换成类。
findClass方法:jdk1.2以后loadClass 的缺省实现调用这个新方法。findClass 的用途包含您的 ClassLoader 的所有特殊代码,而无需要复制其它代码(例如,当专门的方法失败时,调用系统 ClassLoader)。
getSystemClassLoader: 如果覆盖 findClass 或 loadClass,getSystemClassLoader 使您能以实际 ClassLoader 对象来访问系统 ClassLoader(而不是固定的从 findSystemClass 调用它)。
getParent:为了将类请求委托给父代 ClassLoader,这个新方法允许 ClassLoader 获取它的父代 ClassLoader。当使用特殊方法,定制的 ClassLoader 不能找到类时,可以使用这种方法。
resolveClass: 可以不完全地(不带解析)装入类,也可以完全地(带解析)装入类。当编写我们自己的 loadClass 时,可以调用 resolveClass,这取决于 loadClass 的 resolve 参数的值。
findLoadedClass:充当一个缓存,当请求 loadClass 装入类时,它调用该方法来查看 ClassLoader 是否已装入这个类,这样可以避免重新装入已存在类所造成的麻烦。应首先调用该方法。
二、工作流程:
1)调用 findLoadedClass(String) 来查看是否存在已装入的类,如果没有,那么采用那种特殊的神奇方式来获取原始字节。
2)通过父类ClassLoader调用loadClass方法,如果父类ClassLoader是null,那么按缺省方式装入类,即系统ClassLoader。
3)调用findClass(String)去查找类并获取类;
4)如果loadClass 的 resolve 参数的值为true,那么调用 resolveClass 解析 Class 对象.
5)如果还没有类,返回 ClassNotFoundException。
6)否则,将类返回给调用程序。
三、一个实现了ClassLoader的例子:
/**
*CompilingClassLoader.java
*Copyright 2005-2-12
*/
import java.io.*;
public class CompilingClassLoader extends ClassLoader{
//读取一个文件的内容
private byte[] getBytes(String filename) throws IOException{
File file=new File(filename);
long len=file.length();
byte[] raw=new byte[(int)len];
FileInputStream fin=new FileInputStream(file);
int r=fin.read(raw);
if(r!=len) throw new IOException("Can't read all,"+r+"!="+len);
fin.close();
return raw;
}
private boolean compile(String javaFile) throws IOException{
System.out.println("CCL:Compiling "+javaFile+"...");
//调用系统的javac命令
Process p=Runtime.getRuntime().exec("javac "+javaFile);
try{
//其他线程都等待这个线程完成
p.waitFor();
}catch(InterruptedException ie){
System.out.println(ie);
}
int ret=p.exitValue();
return ret==0;
}
public Class loadClass(String name,boolean resovle) throws ClassNotFoundException{
Class clas=null;
clas=findLoadedClass(name);
//这里说明了包的表示
String fileStub=name.replace('.','/');
String javaFilename=fileStub+".java";
String classFilename=fileStub+".class";
File javaFile=new File(javaFilename);
File classFile=new File(classFilename);
//如果存在class文件就不编译
if(javaFile.exists()&&(!classFile.exists()||javaFile.lastModified()>classFile.lastModified())){
try{
if(!compile(javaFilename)||!classFile.exists()){
throw new ClassNotFoundException("ClassNotFoundExcetpion:"+javaFilename);
}
}catch(IOException ie){
throw new ClassNotFoundException(ie.toString());
}
}
try{
byte[] raw=getBytes(classFilename);
//通过读入数据来构造一个类结构,这是核心
clas=defineClass(name,raw,0,raw.length);
}catch(IOException ie){
//
}
if(clas==null){
clas=findSystemClass(name);
}
System.out.println("findSystemClass:"+clas);
if(resovle && clas!=null){
resolveClass(clas);
}
if(clas==null){
throw new ClassNotFoundException(name);
}
return clas;
}
}
测试该loader:
/**
*TestRun.java
*Copyright 2005-2-11
*/
import java.lang.reflect.*;
public class TestRun{
public static void main(String[] args) throws Exception{
String progClass=args[0];
String progArgs[]=new String[args.length-1];
System.arraycopy(args,1,progArgs,0,progArgs.length);
CompilingClassLoader ccl=new CompilingClassLoader();
Class clas=ccl.loadClass(progClass);
//返回一个class的type
Class[] mainArgType={(new String[0]).getClass()};
Method main=clas.getMethod("main",mainArgType);
Object argsArray[]={progArgs};
main.invoke(null,argsArray);
}
}
以上的核心内容已经编写完了,编译后,我们得到两个文件:
CompilingClassLoader.class,TestRun.class
四、编写一个例子,然后运行我们的ClassLoader
/**
*Hello.java
*/
public class Hello{
public static void main(String[] args){
if(args.length!=1){
System.err.println("Error,exit!");
System.exit(1);
}
String name=args[0];
System.out.println("Hello,"+name);
}
}
好了,运行java TestRun Hello 阿飞
....
....
....
Hello,阿飞

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.
