资源描述:
《java代码动态生成java的.class文件.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、目录需要包:2工具类POBuildUtil2工具类BuildUtil6工具类Assistant8RenderClass:27使用例子:29需要包:1.apache-commons-lang-**.jar2.asm-**.jar工具类POBuildUtilimportjava.io.File;importjava.io.FileOutputStream;importjava.util.Collection;importjava.util.Iterator;importorg.apache.commons.lang.WordUtils;importorg.
2、objectweb.asm.ClassWriter;importorg.objectweb.asm.MethodVisitor;importorg.objectweb.asm.Opcodes;publicclassPOBuildUtilextendsClassLoaderimplementsOpcodes{publicClassbuild(Stringclsname,Stringsavepath,Collectionproperties){Classcls=null;try{Stringclassname=BuildUtil.transferClass
3、Name(clsname);ClassWritercw=newClassWriter(false);cw.visit(V1_1,ACC_PUBLIC,classname,null,"java/lang/Object",null);MethodVisitormw=cw.visitMethod(ACC_PUBLIC,"","()V",null,null);mw.visitVarInsn(ALOAD,0);mw.visitMethodInsn(INVOKESPECIAL,"java/lang/Object","","()V");mw.
4、visitInsn(RETURN);mw.visitMaxs(1,1);mw.visitEnd();BuildPropertyproperty=null;Stringpropertytype=null;Stringpropertyname=null;;Iteratoriterator=properties.iterator();while(iterator.hasNext()){property=(BuildProperty)iterator.next();propertytype=BuildUtil.transferClassName(propert
5、y.getType());propertyname=WordUtils.capitalize(property.getName());//System.out.println(propertyname);cw.visitField(ACC_PRIVATE,property.getName(),"L"+propertytype+";",null,null).visitEnd();mw=cw.visitMethod(ACC_PUBLIC,"get"+propertyname,"()L"+propertytype+";",null,null);mw.visi
6、tCode();mw.visitVarInsn(ALOAD,0);mw.visitFieldInsn(GETFIELD,classname,property.getName(),"L"+propertytype+";");mw.visitInsn(ARETURN);mw.visitMaxs(1,1);mw.visitEnd();mw=cw.visitMethod(ACC_PUBLIC,"set"+propertyname,"(L"+propertytype+";)V",null,null);mw.visitCode();mw.visitVarInsn(
7、ALOAD,0);mw.visitVarInsn(ALOAD,1);mw.visitFieldInsn(PUTFIELD,classname,property.getName(),"L"+propertytype+";");mw.visitMaxs(2,2);mw.visitInsn(RETURN);mw.visitEnd();}cw.visitEnd();byte[]code=cw.toByteArray();if(savepath!=null){Assistant.createNewFile(savepath);FileOutputStreamfo
8、s=newFileOutputStream(savepath);fos.write(code)