Summary of the Java reflection mechanism

Source: Internet
Author: User

111111111111

Class<?> cls = class.forname ("package name. Class name");

Object o = cls.newinstance ();

222222222222

Method of Acquisition

method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), boolean.class);// The Boolean here can also be other types such as: integer to see the value of the assignment

333333333333333

Execution method
Method.invoke (O,val); Val is a value that is the value of the Set method above

444444444444444444444444

Get all the methods of the class

Method[] ms = Cls.getmethods ();

Gets the return value type of one of the methods

String type = Ms[0].getreturntype (). GetName ();

return value type:

Java.lang.Long
Java.lang.String

Java.util.Date

Java.lang.Double

Java.lang.Float

Int

Here you can find the corresponding return value based on the name of the method, and then assign the parameter to the second step to get the second step of the method

55555555555555555555555555555555

An Excel import that uses reflection (personal code collection)

Front-end Code

<script type= "Text/javascript" >
$ (function () {
Import the underlying data
$ ("#importData"). Click (function () {
var RQ = $ ("#inpRq"). Val ();
var url = __ctx+ '/zjdlbb/zjdlbb/zjdlbb/importdialog.ht ';
var conf=$.extend ({},{dialogwidth:550, dialogheight:200,help:0,status:0,scroll:0,center:1});
var winargs= "dialogwidth=" +conf.dialogwidth+ "px;dialogheight=" +conf.dialogheight
+ "px;help=" + Conf.help + "; status=" + Conf.status + "scroll=" + conf.scroll + "center=" +conf.center;
Url=url.getnewurl ();
/*killdialog*/
Dialogutil.open ({
Height:conf.dialogHeight,
Width:conf.dialogWidth,
Url:url,
Isresize:true,
Succall:function (RTN) {
$.ligerdialog.success ("Import succeeded", "", function () {
Window.location.reload ();
Window.opener.refreshThis ();
});
}
});
});
});
</script>

<div class= "group" ><a class= "link" id= "ImportData" href= "javascript:;" > Import </a></div>

Background code

@RequestMapping ({"Importexcel"})
@Action (Description = "Import Excel pop-up Windows")
public void Importexcel (Multiparthttpservletrequest request,
HttpServletResponse response) throws Exception {
String RQ = Request.getparameter ("RQ");
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");
SimpleDateFormat sdftime = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat ("yyyy-m-d");
Multipartfile fileload = Request.getfile ("xmlfile");
Resultmessage resultmessage = null;
try {
String FileType = Fileload.getoriginalfilename (). SUBSTRING (
Fileload.getoriginalfilename (). LastIndexOf (".") + 1,
Fileload.getoriginalfilename (). Length ());
Workbook wb = null;
if (filetype.equals ("xls")) {
WB = new Hssfworkbook (Fileload.getinputstream ());
} else if (Filetype.equals ("xlsx")) {
WB = new Xssfworkbook (Fileload.getinputstream ());
} else {
throw new Exception ("Read not Excel file");
}
Sheet Sheet = wb.getsheetat (0);
Xssfsheet s = null;
Hssfcell cell0 = null;
Hssfcell cell1 = null;
map<string, string> map = new hashmap<string, string> ();

Get total number of columns
int Coloumnum=sheet.getrow (0). Getphysicalnumberofcells ();
int Rownum=sheet.getlastrownum ();//Get Total rows

Class<?> cls = Class.forName ("COM.YTD.ZJDLBB.MODEL.ZJDLBB.ZJDLBB");
Method[] ms = Cls.getmethods ();
list<zjdlbb> list = new arraylist<zjdlbb> ();
map<string,string> KeyMap = This.getkey ();
Traverse each row of data, the first row 0 is the title
for (int i = 1; I <= rowNum; i++) {
Object o = cls.newinstance ();
Iterate through each column
for (int j = 0; J < Coloumnum; J + +) {
Get column headers
String title = Sheet.getrow (0). Getcell (j). Getstringcellvalue ();
/* IF (Title.endswith (")")) {
title = Title.substring (0,title.indexof (")");
}*/
Log.info ("title =============================" +title);
Get the value of a column
String colval = Sheet.getrow (i). Getcell (j). Getstringcellvalue ();
Find corresponding entity class properties
String key = Keymap.get (title);
Log.info ("Key =============================" +key);
if (Stringutil.isnotempty (key)) {
Traverse all method Names of a class
for (int k = 0; k < ms.length; k++) {
Getting the Get method
String tmp = "Get" +stringutil.makefirstletteruppercase (key);
When the Excel title is the same as the class property
if (Tmp.equals (Ms[k].getname ()) &&stringutil.isnotempty (Colval)) {
String SetType = Ms[k].getreturntype (). GetName ();
Log.info ("SetType =============================" +settype);
method = null;
if ("Boolean". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), boolean.class);
Method.invoke (O,colval);
}else if ("java.lang.String". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), string.class);
Method.invoke (O,colval);
}else if ("Java.lang.Long". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), long.class);
Method.invoke (O,long.parselong (colval));
}else if ("int". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), integer.class);
Method.invoke (O,integer.parseint (colval));
}else if ("Java.util.Date". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), date.class);
Method.invoke (O,sdftime.parse (colval));
}else if ("Java.lang.Double". Equals (SetType)) {
Log.info ("Hhhhhhh ===========oooooooooooooooooooo==================" +settype);
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), double.class);
Method.invoke (O,double.parsedouble (colval));
}else if ("Java.lang.Float". Equals (SetType)) {
method = Cls.getmethod ("Set" +stringutil.makefirstletteruppercase (key), float.class);
Method.invoke (O,float.parsefloat (colval));
}
}
}
}
}
List.add ((ZJDLBB) o);
}

for (ZJDLBB entity:list) {
Long Id=uniqueidutil.genid ();
Entity.setid (ID);
Zjdlbbservice.add (entity);
}

String result = "Import data succeeded";
if (Result.contains ("Success")) {
Resultmessage = new Resultmessage (1, "Import succeeded!");
} else {
Resultmessage = new Resultmessage (0, result);
}
Writeresultmessage (Response.getwriter (), resultmessage);
} catch (Exception ex) {
Ex.printstacktrace ();
String str = messageutil.getmessage ();
Ex.getlocalizedmessage ();
if (Stringutil.isnotempty (str)) {
Resultmessage = new Resultmessage (0, "Import failed please check that the imported Excel is correct:"
+ str);
Response.getwriter (). print (resultmessage);
} else {
String message = Exceptionutil.getexceptionmessage (ex);
Resultmessage = new Resultmessage (0, "Import failed please check that imported Excel is correct");
Response.getwriter (). print (resultmessage);
}
}
}

Summary of the Java reflection mechanism

Related Article

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.