Home > Back-end >  Changing all the map for the javabean object
Changing all the map for the javabean object

Time:10-24

Changing all the map for the javabean object, there is a field is an enumeration type UserIdentityType, turned not to go, could you tell me how to solve this?


 
Public class DamiUser extends BaseModel {

Primary key name *//*
Public final String KEY_NAME="DamiUser";

User Id/* */
Private String userId.

User id/* type */
Private UserIdentityType userIdentity;

/* */user id number
Private String userIdentityNo;

/* */
create timePrivate String creationTime.
}




 
/* *
* @ Description: changing all the map for the javabean object
* @ Author: Administrator
* @ DateTime: 2020/9/5 15:01
* @ Params: to convert the Map

* @ Return: Bean object*/
Public static & lt; T> T mapToBean (Map Map, T bean) throws the Exception {

BeanMap BeanMap=null;

Try {
BeanMap=beanMap. Create (bean);

BeanMap. PutAll (map);
} the catch (Exception e) {
Throw new Exception (e);
}

Return the bean;
}


The Exception in the thread "main" Java. Lang. Exception: Java. Lang. ClassCastException: Java. Lang. String always be cast to com. JHJK. Dami. Enmu. UserIdentityType
At com. JHJK. Dami. Utils. SysUtil. MapToBean (SysUtil. Java: 139)
At com. JHJK. Dami. MainTests. MapToBean (MainTests. Java: 64)
At com. JHJK. Dami. MainTests. Main (49) MainTests. Java:

CodePudding user response:

It encapsulates a method well, anyway, it's not hard to
 public class Sample {
The static enum EnumTest {
One, Tow, Three;
}
Static class TestBean {
private String name;
Private EnumTest et;
Public String toString () {
Return the String. Format (" name: % s, et: % s ", name, et);
}
}
Public static & lt; T> T mapToBean (Map T beans) map, throws the Exception set {//their encapsulation method, using the reflection of the bean attribute
Class<?> CLS=bean. GetClass ();
Try {
For (Field f: CLS getDeclaredFields ()) {
If (map. Either containsKey (f.g etName ())) {
F.s etAccessible (true);
If (f.g etType (.) isEnum ()) {//if it is enum type
The Object obj=null;
For (Object o: f.g etType () getEnumConstants ()) {//remove all enum values and map the value of the contrast
If (o.t oString (.) the equals (map) get (f.g etName ()))) {//contrast is kept same enum
Obj=o;
break;
}
}
F.s et (bean, obj);//set the bean enum properties
} else {
F.s et (bean, map. Get (f.g etName ()));
}
}
}
} the catch (Exception e) {
Throw new Exception (e);
}

Return the bean;
}
Public static void main (String [] args) {
Try {
Map map=new HashMap<> (a);
The map. The put (" name ", "test");
The map. The put (" et ", "Tow");
TestBean TB=new TestBean ();
MapToBean (map, TB);
System. The out. Println (TB);
} the catch (Throwable e) {
e.printStackTrace();
}
}
}

  • Related