Java 泛型-从类中获取值<;T>;
我有一个类可以将我的jpa实体转换为,反之亦然 当我在方法Java 泛型-从类中获取值<;T>;,java,generics,jpa,reflection,Java,Generics,Jpa,Reflection,我有一个类可以将我的jpa实体转换为,反之亦然 当我在方法converentitylistinotolist中进行转换时,返回的List是List,我需要它是List 是否可以迭代此集合(列表)并获取“TO”值 转换器 public class MyConverter<E, T> implements Serializable { private Class<E> myEntity; private Class<T>
converentitylistinotolist
中进行转换时,返回的List
是List
,我需要它是List
是否可以迭代此集合(列表
)并获取“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;
}
}
你的代码有很多问题。您正在混合对象(例如,类型为
MyEntity
的对象)和表示这些对象的类的对象(例如class
)
所以,当你写作的时候
Class myEntity = (Class) type.getActualTypeArguments()[0];
Class myTO = (Class) type.getActualTypeArguments()[1];
return new MyConverter(myEntity, myTO);
您试图创建一个转换器,将一个类
转换为另一个类
,这没有意义。这就是为什么converentitylistinotolist
的返回类型是类的列表
创建一个包含每个实体的一个实例的转换器也不会产生sens。您应该每次创建一个新实例,或者填充一个作为convert方法参数给定的实例。什么让您认为您正在返回
列表
?是否有错误消息?堆栈跟踪?谢谢回复。该列表被发送到jsf页面(xhtml)。显示一条错误消息:javax.el.PropertyNotFoundException:…“#{item.image}”:在类型java.lang上找不到属性“image”。类“image”是MyTO的属性在不显示jsf页面的情况下,您希望如何获得帮助?什么是item
?我通过添加请求的文件编辑了原始消息。没有添加这些文件,因为它在我不使用通用转换器时工作。如果我填充对象列表(MyTo)而不转换为通用列表,则会正常显示。如果您正在获取列表
,那么您预计如何获取T
类型实例中的值?很容易在类的列表中循环并实例化它们(type.newInstance();
),但我认为您需要以不同的方式来看待这一点。您需要获取实际实例及其值,而不是需要填写的类型。仅仅上课就意味着你没有从正确的事情开始。
Class myEntity = (Class) type.getActualTypeArguments()[0];
Class myTO = (Class) type.getActualTypeArguments()[1];
return new MyConverter(myEntity, myTO);