????3.????????????
????JVM?г??????????????????????????????classloader????????????????????????????ClassLoader??????????дClassLoader????????????????????????       ????????ClassLoader????????????????loadClass()??findClass()??
????????????????????дfindClass()????????????loadClass()???????????дfindClass()??????????????????????????У????????????????
?????????????????д??????????????

 

package snippet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Administrator
*????????????
*/
public class MyClassLoader extends ClassLoader {
// ???java?????????????
public byte[] getBytes(String filename){
File file = new File(filename);
InputStream ips=null;
byte[] b = new byte[(int) file.length()];
try {
ips = new FileInputStream(file);
int raw =ips.read(b);
if(raw!=file.length()){
throw new IOException("?????????????");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(ips!=null){
try {
ips.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return b;
}
public boolean compile(String javaFile){
System.out.println("???????");
Process p=null;
try {
//??????javac????
p=Runtime.getRuntime().exec("javac" + javaFile);
try {
p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int ret = p.exitValue();
return ret==0;
}
@Override
protected Class<?> findClass(String name) {
Class<?> clazz=null;
String fileStub = name.replace("."?? "/");
String javaFileName = fileStub + ".java";
String classFileName = fileStub + ".class";
File javaFile = new File(javaFileName);
File classFile = new File(classFileName);
//???java???????????class??????????????java??????class????????????
if(javaFile.exists()&&(!classFile.exists()||javaFile.lastModified()>classFile.lastModified())){
if(!compile(javaFileName)||!classFile.exists()){
try {
throw new ClassNotFoundException("δ????class???");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//???class??????????????????????????
if(classFile.exists()){
byte[] b = getBytes(classFileName);
clazz = defineClass(name?? b?? 0?? b.length);
}
//??????????????????
if(clazz==null){
try {
throw new ClassNotFoundException(name);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return clazz;
}
}

 

?????????????д??findClass???????????д?÷?????????????????????????
?????????1.?????JVM?????????????????????????????????????????????)????????????????????????ú??Χ
????2.????JVM???????????????????У????棬??????
????3.???????????????????????????ClassLoader??????????????????????loadClass()??findClass()?????????????????