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 (MapMap, 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 topublic 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 (MapT 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 {
Mapmap=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();
}
}
}