用Flex+BlazeDS时,如果你发现flex端传过来的参数是ASObject,而不是对应的Java object,那么你可以写代码手动转换,毕竟ASObject里面已经包含了所对应的Java Object的信息。下面是一些方法,有用了泛型的,有没有的,还有一个转换CriteriaVO的案例方法。
/**
* If flex application is running in debug mode, then you need to manually
* convert ASObject to your concrete object, otherwise you will receive some
* exception like
* "flex.messaging.io.amf.ASObject cannot be cast to your Class X"
* , but in normal mode, you cannot do this, otherwise you will get an
* opposite cast exception.
*
* @param <E>
* @param sourceObjects
* @param targetObjectClass
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
@SuppressWarnings("unchecked")
public static <E> List<E> convertASObject2JavaObject(List<ASObject> sourceObjects, Class<E> targetObjectClass) throws InstantiationException, IllegalAccessException {
List<E> targetObjects = new ArrayList<E>();
ASTranslator ast = new ASTranslator();
for (ASObject aso:sourceObjects) {
targetObjects.add((E) ast.convert(aso, targetObjectClass));
}
return targetObjects;
}
@SuppressWarnings("unchecked")
public static <E> E convertASObject2JavaObject(ASObject sourceObject, Class<E> targetObjectClass){
ASTranslator ast = new ASTranslator();
return (E)ast.convert(sourceObject, targetObjectClass);
}
public static Object convertASObject2JavaObject(ASObject sourceObject){
ASTranslator ast = new ASTranslator();
Object targetObject = null;
try {
targetObject = ast.convert(sourceObject, Class.forName(sourceObject.getType()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return targetObject;
}
/**
* In debug mode, the element type of an list is ASObject, we need to convert it to its
* corresponding java object manually.
* @param criteriaVO
*/
public static void convertASObject2JavaObject(CriteriaVO criteriaVO){
List<FilterCriteriaVO<?>> filterCriterias=new ArrayList<FilterCriteriaVO<?>>();
for(Object o:criteriaVO.getFilterCriteria()){
if(o instanceof ASObject){
filterCriterias.add(convertASObject2JavaObject((ASObject)o,FilterCriteriaVO.class));
}else if(o instanceof FilterCriteriaVO){
filterCriterias.add((FilterCriteriaVO<?>)o);
}
}
criteriaVO.setFilterCriteria(filterCriterias);
List<SortCriteriaVO> sortCriterias=new ArrayList<SortCriteriaVO>();
for(Object o:criteriaVO.getSortCriteria()){
if(o instanceof ASObject){
sortCriterias.add(convertASObject2JavaObject((ASObject)o,SortCriteriaVO.class));
}else if(o instanceof SortCriteriaVO){
sortCriterias.add((SortCriteriaVO)o);
}
}
criteriaVO.setSortCriteria(sortCriterias);
}