import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* 动态的编译Java源文件。它检查.class文件是否存在,.class文件是否比源文件陈旧。
*/
public class CompilingClassLoader extends ClassLoader {
private String path = "";
public CompilingClassLoader(String path) {
this.path = path;
}
/**
* 从磁盘读取指定文件,并返回字节数组
*/
private byte[] getBytes(String className) {
FileInputStream in = null;
byte[] raw = null;
try {
File file = new File(className);
in = new FileInputStream(file);
raw = new byte[(int) file.length()];
int r = in.read(raw);
if (r == file.length()) {
return raw;
}
} catch (IOException ex) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 启动一个进程来编译java源文件
*/
private boolean compile(String javaFile) {
try {
Process p = Runtime.getRuntime().exec("javac " + javaFile);
p.waitFor(); // 等待编译结束
int res = p.exitValue(); // 检查返回码,看编译是否成功
return res == 0;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return false;
}
/**
* 动态的编译Java源文件。它检查.class文件是否存在,.class文件是否比源文件陈旧。
*/
protected Class<?> findClass(String className)
throws ClassNotFoundException {
Class<?> cls = this.findLoadedClass(className);
if (cls == null) {
String fileName = className.replace('.', File.pathSeparatorChar);
String javaFileName = path + fileName + ".java";
String classFileName = path + fileName + ".class";
File javaFile = new File(javaFileName);
File classFile = new File(classFileName);
if (!classFile.exists() && javaFile.exists()
|| javaFile.lastModified() > classFile.lastModified()) {
if (!compile(javaFileName)) {
throw new ClassNotFoundException(className);
}
}
byte[] raw = getBytes(classFileName);
if (raw == null) {
throw new ClassNotFoundException(className);
}
cls = this.defineClass(className, raw, 0, raw.length);
}
return cls;
}
public static void main(String[] args) throws Exception{
CompilingClassLoader ccl = new CompilingClassLoader("e:/");
Class<?> c = ccl.findClass("Test");
Method method = c.getDeclaredMethod("print", new Class<?>[] {});
method.invoke(c.newInstance(), new Object[] {});
}
}
|
public static String beanToString(Object bean)
{
Class c = bean.getClass();
StringBuffer buffer = new StringBuffer();
buffer.append(c.getName() + '[');
while (true)
{
Field[] fields = c.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
try
{
for (int i = 0; i < fields.length; i++)
{
Field f = fields[i];
buffer.append(f.getName());
buffer.append('=');
Object field = f.get(bean);
if (field instanceof Object[])
{
Object[] obj = (Object[])field;
buffer.append(Tool.arrayToString(obj));
}
else
{
buffer.append(field);
}
if (i + 1 < fields.length)
{
buffer.append(',');
}
}
}
catch (Exception e)
{
UspLog.error("toString object error: " + e.toString());
}
c = c.getSuperclass();
if (!c.equals(Object.class))
{
buffer.append(',');
continue;
}
else
{
break;
}
}
buffer.append(']');
return buffer.toString();
}
|