0
我有一個類,將我的jpa實體轉換爲TO,反之亦然。泛型 - 從類獲取價值<T>
當我在方法convertEntityListInTOList
中進行轉換時,List
返回的是List<Class<T>>
,我需要的是List<T>
。
是否可能迭代該集合(List<Class<T>>
)並獲取「TO」值?
轉換
public class MyConverter<E, T> implements Serializable {
private Class<E> myEntity;
private Class<T> myTO;
public MyConverter(Class<E> myEntity, Class<T> myTO) {
this.myEntity = myEntity;
this.myTO = myTO;
}
public List<T> convertEntityListInTOList(List<E> entityList) {
List<T> listTO = new ArrayList<T>();
for(E obj : entityList) {
myTO = convertEntityInTO(obj);
listTO.add(myTO);
}
return listTO;
}
public List<E> convertTOListInEntityList(List<T> listTOs) {
List<E> entityList = new ArrayList<E>();
for(T to : listTOs) {
myEntity = convertTOInEntity(to);
entityList.add(myEntity);
}
return entityList;
}
public T convertEntityInTO(Object myEntity) {
T myTO = createInstanceTO();
if(myEntity != null) {
try {
BeanUtils.copyProperties(myTO, myEntity);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return myTO;
}
public E convertTOInEntity(T myTO) {
E myEntity = createInstanceEntity();
if(myTO != null) {
try {
BeanUtils.copyProperties(myEntity, myTO);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return myEntity;
}
/**
*
* @return
*/
public T createInstanceTO() {
try {
return getMyTO().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @return
*/
public E createInstanceEntity() {
try {
return getMyEntity().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
轉換器生產商
@Produces
public MyConverter create(InjectionPoint ip) {
ParameterizedType type = (ParameterizedType) ip.getType();
Class myEntity = (Class) type.getActualTypeArguments()[0];
Class myTO = (Class) type.getActualTypeArguments()[1];
return new MyConverter(myEntity, myTO);
}
是什麼讓你覺得你回來了'List>'?是否有錯誤訊息?堆棧跟蹤? –
感謝您的回覆。該列表發送到jsf頁面(xhtml)。顯示錯誤消息:javax.el.PropertyNotFoundException:...「#{item.image}」:在java.lang.Class類型中找不到屬性'image' 'image'是MyTO的屬性 – gfinotti
您如何看待在不顯示jsf頁面的情況下獲得幫助?什麼是「物品」? –