标签:ack dex you write main static pool on() tst
自定义文件系统类加载器public class Loader extends ClassLoader{
private String dir;
public Loader(String dir)
{
this.dir=dir;
}
@Override
protected Class<?> findClass(String name)throws ClassNotFoundException
{
Class<?> c=findLoadedClass(name);
if(null!=c)
{
return c;
}else
{
ClassLoader parent=this.getParent();
try {
c=parent.loadClass(name);
}catch(Exception e)
{
//e.printStackTrace();
}
if(c!=null)
{
return c;
}else
{
byte[] data=getData(name);
if(data==null)
{
throw new ClassNotFoundException();
}else
{
c=defineClass(name,data,0,data.length);
System.out.println("yes");
}
}
}
return c;
}
private byte[] getData(String classname)
{
String path=dir+"/"+classname.replace(‘.‘, ‘/‘)+".class";
InputStream is=null;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
try {
is=new FileInputStream(path);
int len=-1;
byte[] buffer=new byte[1024];
while((len=is.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
bos.flush();
return bos.toByteArray();
}catch(IOException e)
{
e.printStackTrace();
return null;
}finally {
try {
if(null!=is)
{
is.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
try {
if(null!=bos)
{
bos.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}
javassist 创建java文件,然后使用自定义类加载器加载
public class One {
public static void main(String[] args) throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.makeClass("com.sxt.in.HelloWorld");
CtMethod m=CtMethod.make("public static void main(String[] args){System.out.println(\"aa\");}", cc);
cc.addMethod(m);
cc.writeFile("d:/myjava");
Loader loader =new Loader("d:/myjava");
Class<?> c=loader.loadClass("com.sxt.in.HelloWorld");
System.out.println(c.getClassLoader());
}
}
cmd编译创建的java文件:
C:\Users\10853>d:
D:\>cd myjava
D:\myjava>javac -d . HelloWorld.java
D:\myjava>java com.sxt.in.HelloWorld
aa
D:\myjava>
标签:ack dex you write main static pool on() tst
原文地址:https://blog.51cto.com/14437184/2439132