2019-03-19 ecj、通过绝对路径加载类、通过命令debug

1、ecj编译代码(不需要传类名,它会自动编译test文件加下所有的类)
String[] str = {"C:\Users\Administrator\Desktop\test\"};
(new Main(new PrintWriter(System.out), new PrintWriter(System.err), true, (Map)null, (CompilationProgress)null)).compile(str);

2、通过绝对路径加载类
首先自定义自己的类加载器:
package com.myframe;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
private String url;
public MyClassLoader(String url){
this.url = url;
}
@Override
protected Class findClass(String name) {
Class c = findLoadedClass(name);
if (c!=null){
return c;
}
byte[] classdata = new byte[0];
try {
classdata = getClassData(name);
} catch (Exception e) {
e.printStackTrace();
}
//通过二进制数据定义类
c=defineClass(name,classdata ,0 ,classdata.length );
return c;
}
//读取所有的类(class文件),转化为二进制数组
private byte[] getClassData(String className) throws Exception {
byte[] classData;
InputStream in = new FileInputStream(url);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int temp = 0;
while ((temp=in.read(buffer))!=-1){
byteArrayOutputStream.write(buffer, 0, temp);
}
classData = byteArrayOutputStream.toByteArray();
if (in != null){
in.close();
}
if (byteArrayOutputStream != null){
byteArrayOutputStream.close();
}
return classData;
}
}

然后获取加载类:
String str1 = "C:\Users\Administrator\Desktop\test\Read.class";
//获取类的绝对路径
System.out.println(Test1.class.getClassLoader().getResource("").toString());
MyClassLoader m = new MyClassLoader(str1);
Class c = m.loadClass("Read");
System.out.println(c.getName());

3、通过命令debug代码
javac -g test.java //用debug编译代码
jdb //进入jdb,之后可以设置断点(stop at test:10)
run test //运行程序
cont//继续执行程序到下一个断点

你可能感兴趣的:(2019-03-19 ecj、通过绝对路径加载类、通过命令debug)