我有一个类可以将我的 jpa 实体转换为 TO,反之亦然。
当我在方法 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);
}
最佳答案
您的代码存在很多问题。您正在混合对象(例如 MyEntity
类型的对象)和表示这些对象的类的对象(例如 Class<MyEntity>
)。
所以,当你写
Class myEntity = (Class) type.getActualTypeArguments()[0];
Class myTO = (Class) type.getActualTypeArguments()[1];
return new MyConverter(myEntity, myTO);
您正在尝试创建一个转换器来转换 Class
进入另一个Class
,这没有意义。这就是为什么返回类型为 convertEntityListInTOList
是一个类列表。
创建一个包含每个实体的一个实例的转换器也没有意义。您应该每次创建一个新实例,或者填充作为参数传递给转换方法的实例。
关于java - 泛型 - 从 Class<T> 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918525/