"Dynamic Pages" (c) bis: Read the class and attribute names of the jar packages with custom annotations

Source: Internet
Author: User

The previous blog describes the class name and property name of the jar package read through reflection, but the problem is that the Chinese annotation and attribute types of the class name and property name are not readable. So the previous blog has buried a hint that the class name, property name, Chinese annotation, and attribute type of the jar package are read through custom annotations. Let's talk about how this blog is implemented.

First of all, because our jar package is not placed under the project, so we think how to add the jar package, so we do a similar to upload a file, the jar upload, and then read the jar package inside the class name, property name and other properties, and then add to the database. The overall idea has been determined, and the following will be implemented.

The first is to upload the jar package. I have previously written springmvc file upload blog, specifically can refer to the blog I wrote earlier.

/** * Jar Package Upload * @param request * @param response * @return * @throws illegalstateexception * @throws ioexception * * @Request Mapping ("/upload2") public String upload2 (httpservletrequest request,httpservletresponse response) throws IllegalStateException, Ioexception{commonsmultipartresolver multipartresolver = new Commonsmultipartresolver ( Request.getsession (). Getservletcontext ());//Determine if the request contains a multipart type of data if (Multipartresolver.ismultipart ( Request) {//To cast the request to multiparthttpservletrequest type multiparthttpservletrequest multirequest = ( Multiparthttpservletrequest) request;//uses an iterator to determine how many files there are, and a way to traverse the file iterator<string> iter = Multirequest.getfilenames (); while (Iter.hasnext ()) {///The role of an iterator is to take a file and take it to multipartfile file = Multirequest.getfile (String) Iter.next ()) (if (file! = null) {//Get file after output file//First define file name String FileName = File.getoriginalfilename ();//define output path string path = "g:/" + fileName; String Fromfilepath = "g:\\" + filename;//initialization File LocalFile = new file (path);//use STRINGMVC to give us a way to write it to local FIle.transferto (LocalFile); try {getjarname (Fromfilepath, request, response);} catch (Exception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}} return "/uploadjarbag";

Here's how to prepare for custom annotations, customizing an annotation parser

Package Com.tgb.itoo.uisystem.entity;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * Define an annotation parser * @author Hi-Welcome * @date March 11, 2015 10:10:49 * */@Retention (Retentionpolicy.runtime)//annotations are present in the class bytecode file and can be obtained through reflection at run time @Target ({ Elementtype.field,elementtype.method,elementtype.type})//Define the action target of the annotation * * scope field, enumerated constant/method @Documented// Note that the note will be included in Javadoc public @interface Fieldmeta {/** * is a serial number * @return */boolean ID () default false      ;              /** * Field Name * @return */String name () default "";             /** * Field length, default value is 255 * @return */int length () default 255;      /** * Editable * @return * * * Boolean editable () default true;      /** * is displayed in the list * @return */Boolean summary () default true; /** * Field Description * @return */String DescriptiOn () default ""; }
define a Help class to get annotations
Package Com.tgb.itoo.uisystem.controller;import Java.lang.reflect.field;import com.tgb.itoo.uisystem.entity.fieldmeta;/** * Get help for annotations * @author yingying * @date March 11, 2015 10:12:15 * */public class Sortablefi          eld {public Sortablefield () {} public Sortablefield (Fieldmeta Meta, field field) {super ();          This.meta = meta;         This.field = field;              This.name=field.getname ();      This.type=field.gettype ();          } public Sortablefield (Fieldmeta Meta, field field, int length) {super ();          This.meta = meta;         This.field = field;              This.name=field.getname ();         This.type=field.gettype ();    This.length=length;          } public Sortablefield (Fieldmeta Meta, String name, int length, class<?> type) {super ();          This.meta = meta;         THIS.name = name;        this.length = length;      This.type = type;      } private Fieldmeta meta;      private Field field; PrivAte String name; private int length;public int getlength () {return length;} public void setLength (int length) {this.length = length;}            Private class<?> type;      Public Fieldmeta Getmeta () {return meta;      } public void Setmeta (Fieldmeta meta) {this.meta = meta;      } public field GetField () {return field;      } public void SetField (Field field) {This.field = field;      } public String GetName () {return name;      } public void SetName (String name) {this.name = name;      } public class<?> GetType () {return type;      } public void SetType (class<?> type) {this.type = type; } }

Read the properties of a jar package from a custom annotation

/** * Read the class name and property name of the jar package * @param jarfile * @throws Exception */public void Getjarname (String jarfile, HttpServletRequest reque St, httpservletresponse response) throws Exception {//Define an annotation helper class type listlist<sortablefield> list = new ArrayList  <SortableField> (); try{//creates a new file instance by converting the given pathname string to an abstract path name file F = new file (jarfile); URL Realurl = F.touri (). Tourl (); URLClassLoader Myclassloader = new URLClassLoader (new Url[]{realurl},thread.currentthread (). GetContextClassLoader () )///through Jarfile and Jarentry get all class jarfile jar = new Jarfile (jarfile);//Returns the enumeration of ZIP file entries enumeration<jarentry> EnumFiles = Jar.entries (); Jarentry entry;//Tests If this enumeration contains more elements while (enumfiles.hasmoreelements ()) {entry = (jarentry) enumfiles.nextelement (); Entry.getname (). IndexOf ("Meta-inf") <0) {//Find in string entry the first occurrence of "meta-inf" in the position string classfullname = Entry.getname (); if (Classfullname.indexof (". Class") <0) {//Find the first occurrence of ". Class" in the string classfullname Classfullname = Classfullname.substring (0,classfullname.length ()-1);} else{//remove the suffix. classsTring ClassName = classfullname.substring (0,classfullname.length ()-6). Replace ("/", "."); String strclassname=classname.substring (Classname.lastindexof (".") +1, Classname.length ()); System.out.println ("Last intercepted class name:" + strclassname); class<?> MyClass = Myclassloader.loadclass (className);//Get Properties by Class object field[] fields =  Myclass.getdeclaredfields (); This gets four fields entities Entitieslist = new entities ();//Get Annotations on class Fieldmeta meta111 = Myclass.getannotation (fieldmeta.class );  System.out.println ("Chinese Note for Class name:" + meta111.name ()); Entitieslist.setentitydesc (Meta111.name ()); The Chinese description of the class name (Chinese note) for (field F1:fields) {//Get Fieldmeta annotation in field contains fieldmeta meta = f1.getannotation (fieldmeta.c                  LASS);                System.out.println ("Print Length:" + meta.length ());                System.out.println ("Print type:" + F1.gettype (). GetName ());                String Getpropertytype = F1.gettype (). GetName (). toString (); String Strpropertytype = getpropertytype.substring (Getpropertytype.lastindexof (".") +1, Getpropertytype.length ());                System.out.println ("Last intercepted attribute type:" + strpropertytype);                                  if (meta!=null) {Sortablefield SF = new Sortablefield (meta, F1); System.out.println ("Field name:" +l.getname () + "\ t field type:" +l.gettype () + "\ t annotation name:" +l.getmeta (). Name () + "\ t annotation Description:" +                          L.getmeta (). Description ());                                 System.out.println ("Field name:" +l.getname ());  Add the property name and class name to the entity Entitieslist.setentityname (strClassName);  Class name Entitieslist.setdatatype (Strpropertytype);  Property Type//entitieslist.setdatatype (Meta.getclass (). Gettypename ()); Entitieslist.setdatalength (Meta.length ());   Length Entitieslist.setpropertyname (F1.getname ());  Property name Entitieslist.setpropertydesc (Sf.getmeta (). name ());                                                                                 The Chinese description of the attribute name (Chinese note) entitiesbean.addjartotable (entitieslist); }}}}}} catch (IOException e) {e.printstacktrace ();}}

here, the class name of the jar package, the property name including the Chinese annotation, and the property type can be read by customizing the annotations. I uploaded a jar package: http://download.csdn.net/detail/huanjileaimeidan/8548345 This is the jar package that I uploaded to test, interested in downloading and trying, If you have any questions, please leave a message at the bottom and welcome to communicate with me.


"Dynamic Pages" (c) bis: Read the class and attribute names of the jar packages with custom annotations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.