Map to bean map to Bean

Source: Internet
Author: User

Package com. Wen. test;

Import java. Lang. Reflect. field;
Import java. Lang. Reflect. method;
Import java. Math. bigdecimal;
Import java. Text. simpledateformat;
Import java. util. date;
Import java. util. hashmap;
Import java. util. Map;

Public class test {

/**
* Map to Bean
* @ Param mpfrom
* @ Param objto
* @ Return
*/
Public static object maptobean (MAP mpfrom, object objto ){
Object [] objkeys = mpfrom. keyset (). toarray ();
String strfieldname = "";

Try {
For (Object objkey: objkeys ){
Strfieldname = objkey. tostring ();

Field objfield = objto. getclass (). getdeclaredfield (
Strfieldname. tolowercase ());
Objfield. setaccessible (true );

Objfield. Set (objto, mpfrom. Get (strfieldname ));
}
} Catch (exception e ){
E. printstacktrace ();
}
Return objto;
}

/**
* Map to Bean
* @ Param Map
* @ Param CLS
* @ Return
*/
Public static object map2bean (MAP map, class CLs ){
Object OBJ = NULL;
Try {
OBJ = Cls. newinstance ();
} Catch (exception e ){
E. printstacktrace ();
}
// Retrieve all the methods in bean
Method [] Methods = Cls. getmethods ();
For (INT I = 0; I <methods. length; I ++ ){
// Obtain the method name
String method = methods [I]. getname ();
// Type of the fetch Method
Class [] cc = methods [I]. getparametertypes ();
If (CC. length! = 1)
Continue;

// If the method name does not start with set, exit this
If (method. indexof ("set") <0)
Continue;
// Type
String type = Cc [0]. getsimplename ();

Try {
// Convert to lowercase
// Object value = method. substring (3). tolowercase ();
Object value = method. substring (3, 4). tolowercase ()
+ Method. substring (4 );
System. Out. println ("value =" + value );
// If the key exists in the map
If (Map. containskey (value) & map. Get (value )! = NULL ){
// Call its underlying method
Setvalue (type, map. Get (value), I, methods, OBJ );
}
} Catch (exception e ){
E. printstacktrace ();
}
}
Return OBJ;
}

/*************************************** ************************************
* Call the underlying method setting value
*/
Private Static void setvalue (string type, object value, int I,
Method [] method, object bean ){
If (value! = NULL &&! Value. Equals ("")){
Try {
If (type. Equals ("string ")){
// The first parameter: The second parameter of the object from which the basic method is called: The parameter used for method call
Method [I]. Invoke (bean, new object [] {value });
} Else if (type. Equals ("int") | type. Equals ("integer ")){
Method [I]. Invoke (bean, new object [] {New INTEGER (""
+ Value )});
} Else if (type. Equals ("double") | type. Equals ("double ")){
Method [I]. Invoke (bean, new object [] {New Double (""
+ Value )});
} Else if (type. Equals ("float") | type. Equals ("float ")){
Method [I]. Invoke (bean, new object [] {New float (""
+ Value )});
} Else if (type. Equals ("long") | type. Equals ("long ")){
Method [I]. Invoke (bean,
New object [] {New Long ("" + value )});
} Else if (type. Equals ("Boolean") | type. Equals ("Boolean ")){
Method [I]. Invoke (bean, new object [] {Boolean. valueof (""
+ Value )});
} Else if (type. Equals ("bigdecimal ")){
Method [I]. Invoke (bean, new object [] {New bigdecimal (""
+ Value )});
} Else if (type. Equals ("date ")){
Date = NULL;
If (value. getclass (). getname (). Equals ("Java. util. date ")){
Date = (date) value;
} Else {
String format = (string) value). indexof (":")> 0? "Yyyy-mm-dd hh: mm: SS"
: "Yyyy-mm-dd ";
Simpledateformat Sf = new simpledateformat ();
SF. applypattern (format );
Date = SF. parse (string) (value ));
}
If (date! = NULL ){
Method [I]. Invoke (bean, new object [] {date });
}
} Else if (type. Equals ("byte []") {
Method [I]. Invoke (bean,
New object [] {New String (Value + ""). getbytes ()});
}
} Catch (exception e ){
System. Out
. Println ("An error occurred while filling the value in linkhashmap or hashtable into JavaBean. Please check! ");
E. printstacktrace ();
}
}
}


Public static void main (string [] ARGs ){
User user = new user ();
Map map = new hashmap ();
// Map. Put ("userid", "123 ");
// Map. Put ("username", "username123 ");
// Map. Put ("usertel", "usertel123 ");
Map. Put ("Age", 234 );
Map. Put ("CREATE", new date ());
Map. Put ("currency", new bigdecimal (123). setscale (2 ));
Map. Put ("score", 23.33323 );
Long start = system. currenttimemillis ();
User = (User) map2bean (MAP, user. getclass ());
Long end = system. currenttimemillis ();
System. Out. println ("time =" + (end-Start ));
System. Out. println (user. tostring ());
}
}
 
Class user {

Private string userid;
Private long age;
Private Double score;
Private date create;

Private string username;
Private bigdecimal money;

Private string usertel;

Public String getuserid (){
Return userid;
}

Public void setuserid (string userid ){
This. userid = userid;
}

Public String GetUserName (){
Return username;
}

Public void setusername (string username ){
This. Username = username;
}

Public String getusertel (){
Return usertel;
}

Public void setusertel (string usertel ){
This. usertel = usertel;
}

/**
* @ Return the age
*/
Public long getage (){
Return age;
}

/**
* @ Param age the age to set
*/
Public void setage (long age ){
This. Age = age;
}

/* (Non-javadoc)
* @ See java. Lang. Object # tostring ()
*/
@ Override
Public String tostring (){
System. Out. println ("age =" + age );
System. Out. println ("usertel =" + usertel );
System. Out. println ("username =" + username );
System. Out. println ("userid =" + userid );
System. Out. println ("score =" + score );
System. Out. println ("create =" + create );
System. Out. println ("Money =" + money );
Return super. tostring ();
}

/**
* @ Return the score
*/
Public double getscore (){
Return score;
}

/**
* @ Param score the score to set
*/
Public void setscore (Double score ){
This. Score = score;
}

/**
* @ Return the create
*/
Public date getcreate (){
Return create;
}

/**
* @ Param create the create to set
*/
Public void setcreate (date create ){
This. Create = create;
}

/**
* @ Return the money
*/
Public bigdecimal getmoney (){
Return money;
}

/**
* @ Param money the money to set
*/
Public void setmoney (bigdecimal money ){
This. Money = money;
}


}

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.