Search code examples
javajava-8type-conversionstruts2

How to convert Bean to Object and how to retrieve Bean from Object in Java


I have following bean file.and I would like to put this bean to Map<String, Object> as key of bean.

Bean.java

@SuppressWarnings("serial")
public class bean implements Serializable {
    @Getter @Setter
    private param
 }

BaseAction.java

public class BaseAction extends ActionSupport implements SessionAware {
    // session
    @Getter @Setter
    protected Map<String, Object> session;
    
    public execute(){
     session.put("loginUser", "userA");
     session.put("bean", bean);
     session.get("bean");
   }

}

After execute above setter,I retrieve this Bean by following getter. It seems that session.get("bean") seems to be regarded as Object. and caught some error , so that we cannot use bean's setter and getter.

 @Getter @Setter
 private Bean bean= new Bean();

setBean(session.get("bean"))

method setBean(Bean) is not applicable for the arguments(Object) 

Are there any good way to put bean to Map<String, Object> ?


Solution

  • The session Map is implemented as Map<String, Object>, and you need to keep types at least to the setter method of the SessionAware interface.

    You can convert any object you put into the session to different types using Struts Type Conversion. Since you injected a session object from the action context, it gets and puts objects to the #session via OGNL on the view layer. It uses property accessors of the objects to get its values. You still keep the value as Object in the Struts tags attributes.

    If you know the instance type of the object you put into the session then you can always convert to string values to this type from parameters of the request. No need to explicitly typecast to the instance type.

    The following code will work the same as above.

    @Getter @Setter
    private Object bean= new Bean();
    
    setBean(session.get("bean"))