java代码动态生成java的.class文件

上传人:小** 文档编号:76362716 上传时间:2022-04-18 格式:DOC 页数:31 大小:202KB
收藏 版权申诉 举报 下载
java代码动态生成java的.class文件_第1页
第1页 / 共31页
java代码动态生成java的.class文件_第2页
第2页 / 共31页
java代码动态生成java的.class文件_第3页
第3页 / 共31页
资源描述:

《java代码动态生成java的.class文件》由会员分享,可在线阅读,更多相关《java代码动态生成java的.class文件(31页珍藏版)》请在装配图网上搜索。

1、目录使用例子: 29使用例子: 29雲亜旬-需要包:工具类 POBuildUtil 2工具类 BuildUtil 6工具类 Assistant 827RenderClass:使用例子: 29需要包:1. apache-commons-lang-*.jar2. asm-*.jar工具类 POBuildUtilimport java.io.File;import java.io.FileOutputStream;import java.util.Collection;import java.util.Iterator;import mons.lang.WordUtils;import org.ob

2、jectweb.asm.ClassWriter;import org.objectweb.asm.MethodVisitor;import org.objectweb.asm.Opcodes;public class POBuildUtil extends ClassLoader implements Opcodes public Class build(String clsname,String savepath,Collection properties)Class cls = null;tryString classname = BuildUtil.transferClassName(c

3、lsname); ClassWriter cw = new ClassWriter(false);cw.visit(V1_1, ACC_PUBLIC, classname, null, java/lang/Object, null);MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, , ()V, null, null);mw.visitVarInsn(ALOAD, 0);mw.visitMethodInsn(INVOKESPECIAL, java/lang/Object, , ()V);mw.visitInsn(RETURN);mw.visitMaxs

4、(1, 1);mw.visitEnd();BuildProperty property = null;String propertytype = null;String propertyname = null;Iterator iterator = properties.iterator();while (iterator.hasNext()property = (BuildProperty)iterator.next();propertytypeBuildUtil.transferClassName(property.getType();propertyname = WordUtils.ca

5、pitalize(property.getName(); /System.out.println(propertyname);cw.visitField(ACC_PRIV ATE, property.getName(), L+propertytype+;, null, null).visitEnd();mw = cw.visitMethod(ACC_PUBLIC,get+propertyname, ()L+propertytype+;, null,null);mw.visitCode();mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD

6、, 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(ALOAD, 0);mw.visitVarInsn(ALOAD, 1);mw.visitFieldInsn(PUTFIELD,property.getName(),L

7、+propertytype+;); mw.visitMaxs(2, 2); mw.visitInsn(RETURN); mw.visitEnd();cw.visitEnd();byte code = cw.toByteArray();if (savepath!=null)Assistant.createNewFile(savepath);FileOutputStream fosFileOutputStream(savepath);fos.write(code);fos.close();classname,newcls = this.defineClass(clsname, code, 0, c

8、ode.length);return cis name.replace(/);return cis name.replace(/);catch (Throwable e)e.pri ntStackTrace();return cls; public class BuildUtil 工具类uildUtilpublic staticStri ng tran sferClassName(Class cls)String cls name = cls.getName();return cls name.replace( ., /);public static Stri ng tran sferClas

9、sName(Stri ngcls name)一. 工具类 BuildProperty public class BuildPropeiprivateStri ngn ame;privateStri ngtype ;publicBuildProperty()public BuildProperty(Stri ng n ame,Stri ng type)this . name = name;this . type = type;public String getName() returnn ame;public void setName(Stri ng n ame) this . name = n

10、ame;public String getType() return type ;public void setType(String type) this . type = type;工具类 Assistantimport java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.Out

11、putStreamWriter;import java.text.SimpleDateFormat;import java.util.Calendar;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;public class Assistant private static final Logger log = Logger.getLogger(Assistant.class);public static String

12、convertRequestParameter(String parameter) throws Exceptionreturn convertRequestParameter(parameter,null);public static String convertRequestParameter(String parameter,String format) throws Exceptionif (parameter!=null)if (format=null) format=utf-8;parameter = .URLDecoder.decode(parameter,format); re

13、turn parameter;public static boolean notEmpty(HttpServletRequest request,String key)if (request.getParameter(key)!=null &request.getParameter(key).length()0)return true;elsereturn false;url,Stringpublic static void writeFileContent(String content ,ServletContext context) throws ExceptionwriteFileCon

14、tent( getFullPath(url,context),content);public static String HTMLEncode(String txt) if (txt!=null & txt.length()0)txt=txt.replaceAll(&,&); txt=txt.replaceAll(,>);txt=txt.replaceAll(,");txt=txt.replaceAll(,’);return txt;public static boolean existFile(String urlpath,ServletContext co

15、ntext)File file = new File(getFullPath(urlpath, context);if (file.exists()return true;elsereturn false;public static void writeFileContent(String path,String content) throwsExceptionFile file = new File(path);if (!file.exists()file.createNewFile();OutputStreamWriter write= new OutputStreamWriter(new

16、 FileOutputStream(file),GBK);BufferedWriter writer=new BufferedWriter(write); writer.write(content);writer.close();write.close();public static String getFileContent(String url,ServletContext context) throws ExceptionString filepath = getFullPath(url,context);return getFileContent(filepath);public st

17、atic String getFileContent(String path) throws ExceptionStringBuffer buf = new StringBuffer();File file = new File(path);if (file.exists()InputStreamReader read = new InputStreamReader(new FileInputStream(file),GBK);BufferedReader reader=new BufferedReader(read);tryString content = reader.readLine()

18、;while (content!=null)buf.append(content);content = reader.readLine();finallyif (reader!=null) reader.close();if (read!=null)read.close();return buf.toString();/? ? ?(? ? )public static java.util.Date addTimeByDay(java.util.Date date,int days)throws ExceptionCalendar calendar=Calendar.getInstance();

19、 calendar.setTime(date);calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+days); return calendar.getTime();public static java.util.Date addTimeByMinutes(java.util.Date date,int minutes) throws ExceptionCalendar calendar=Calendar.getInstance(); calendar.setTime(date);calendar.set(Calendar.MINUTE

20、,calendar.get(Calendar.MINUTE)+minute s);return calendar.getTime();public static java.util.Date addTimeBySeconds(java.util.Date date,int seconds) throws ExceptionCalendar calendar=Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.SECOND,calendar.get(Calendar.SECOND)+secon ds);retur

21、n calendar.getTime();public static java.util.Date nowTime() throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd);String datestr = sdf.format(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);public static java.util.Date nowFullTime() throws ExceptionSimpleDateFo

22、rmat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);String datestr = sdf.format(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);public static java.util.Date nowFullTime(String format) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(format);String datestr = sdf.forma

23、t(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);public static String convertDateStrToString(String datestr,String format) throws ExceptionString result = null;SimpleDateFormat sdf = new SimpleDateFormat(format); tryresult = sdf.format(sdf.parse(datestr);catch (Exception ex)sdf

24、 = new SimpleDateFormat(yyyy-MM-dd);result = sdf.format(sdf.parse(datestr);return result;public static String convertDateToString(java.util.Date date,String format) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date);public static java.util.Date formatDateStr

25、(String datestr) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd);return sdf.parse(datestr);public static java.util.Date formatDateStr(String datestr,String format) throws Exceptionjava.util.Date result = null;SimpleDateFormat sdf = new SimpleDateFormat(format);tryresult = sdf

26、.parse(datestr);catch (Exception ex)sdf = new SimpleDateFormat(yyyy-MM-dd);result = sdf.parse(datestr);return result;public static java.util.Date formatFullDateStr(String datestr) throws Exceptionjava.util.Date result = null;SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);tryresult

27、= sdf.parse(datestr);catch (Exception ex)sdf = new SimpleDateFormat(yyyy-MM-dd);result = sdf.parse(datestr);return result;public static String getFileName(String filepath)filepath = filepath.replace(/, );String filename = filepath;if (filepath.lastIndexOf()0)filename = filepath.substring(filepath.la

28、stIndexOf()+1);return filename;public static void copy(ServletContext context,String form,String to ,boolean removeold) throws java.io.IOExceptioncopy(getFullPath(form,context),getFullPath(to,context),removeold);to,boolean/? ? ? ? ? ? ? ? removeold ? ? ? ? ? public static void copy( String from, Str

29、ing removeold )throws java.io.IOExceptionint BUFF_SIZE = 1024;byte buffer = new byte BUFF_SIZE ; java.io.InputStream in = null;java.io. OutputStream out = null;tryin = new FileInputStream( from );out = new FileOutputStream( to );while ( true )synchronized ( buffer )int amountRead = in.read( buffer )

30、;if ( amountRead = -1 )break;out.write( buffer, 0, amountRead );finallyif ( in != null )in.close();if ( out != null )out.close();System.out.println(Copy Finish);if (removeold)java.io.File file =new java.io.File(from);if (file.delete()System.out.println(delete file:+file.getPath();file.delete();publi

31、c static String getUploadPath(String path)if (path.indexOf(/)!=0)path = /+path;if (path.lastIndexOf(/)!=path.length()-1)path = path+/;return path;/? ? ? ?public static String getFullPath(String url,ServletContext context) url = url.replace(, /);String path = context.getRealPath(url);return path.repl

32、ace(/, );/? ?public static boolean deleteFile(String url,ServletContext context) throws Exception java.io.File file =new java.io.File(getFullPath(url.replace(/,),context);String filepath = file.getPath();String ext = filepath.substring(filepath.lastIndexOf(.)+1);String minifilepath =filepath.substri

33、ng(0,filepath.lastIndexOf(.)+_mini.+ext;java.io.File minifile = new java.io.File(minifilepath);if (minifile.exists()minifile.delete();if (file.exists()log.debug(delete file:+file.getPath(); return file.delete();return false;public static String createPathByDate(String url,ServletContext context)Stri

34、ng fullpath = getFullPath(url,context);if (fullpath.lastIndexOf()!=fullpath.length()-1) fullpath +=;Calendar nowtime = Calendar.getInstance();fullpath +=String.valueOf(nowtime.get(Calendar.YEAR)+; SimpleDateFormat sdf = new SimpleDateFormat(MMdd); fullpath+=sdf.format(nowtime.getTime()+;File file =

35、new File(fullpath);if (!file.exists() file.mkdirs();if (url.lastIndexOf()!=url.length()-1 & url.lastIndexOf(/)!=url.length()-1)url +=/;url += String.valueOf(nowtime.get(Calendar.YEAR)+/;url += sdf.format(nowtime.getTime()+/;return url;public static boolean createPath(String path,ServletContext conte

36、xt) throws ExceptionString fullpath = getFullPath(path,context);File file = new File(fullpath); boolean result= true;if (!file.exists()result =file.mkdirs();return result;II ?讹??public static String getContextUrl(String url,HttpServletRequest request,ServletContext context)if(request.getContextPath(

37、)!=null&request.getContextPath().length()0)if (url.indexOf(/)!=0) url = /+url;url = request.getContextPath()+url; return url;? ? ? request? ?貳?public static Object getValue(HttpServletRequest request,String key)if (notEmpty(request, key)return request.getParameter(key); elsereturn request.getAttribu

38、te(key);public static void createNewFile(String savepath) throws java.io.IOExceptionint pos = savepath.lastIndexOf();String dir = savepath.substri ng(0,pos);File directory 二new File(dir);if (!directory.exists()directory.mkdirs();File file = new File(savepath); if (file.exists()file.createNewFile();R

39、enderClass:package com.zte nc.proj.table.f un cti on;import java.util.List;/* ?*/publicclassRen derClass /* ?*/private StringclassName/* ?*/private StringclassPath/* ?*/private Listpropertiespublic Ren derClass() properties =n ull public String getClassName() retur nclassName ;public void setClassNa

40、me(Stri ng className) this . className = className;public Stri ng getTableName() return tableName ;public void setTableName(Stri ng tableName) this . tableName = tableName;publicLisgetProperties() return propertiespublic void setProperties(List properties) this . properties = properties;public void setClassPath(Stri ng classPath) this . classPath = classPath;public Stri ng getClassPath() return classPath使用例子:POBuildUtil utilnew POBuildUtil。;util.build(rc.getClassName(),rc.getClassPat,rc.getProph()+ +rc.getTableName()+ .class erties();/ 在这里成功生成。 class 文件注:以上代码均来自于网上资料。可直接复制即可使用

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!