在我写一个REST服务器通用的,我有一个包单品数的集合类从我的服务返回:做一个集合的javax.xml.bind
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "person_collection")
public final class PersonCollection {
@XmlElement(name = "person")
protected final List<Person> collection = new ArrayList<Person>();
public List<Person> getCollection() {
return collection;
}
}
我想重构这些使用泛型这样的样板代码可以在超类中实现:
public abstract class AbstractCollection<T> {
protected final List<T> collection = new ArrayList<T>();
public List<T> getCollection() {
return collection;
}
}
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "person_collection")
public final class PersonCollection extends AbstractCollection<Person> {}
如何设置在超集合@XmlElement
注解?我正在考虑一些涉及@XmlJavaTypeAdapter
和反思的内容,但希望更简单些。如何创建JAXBContext
?顺便说一下,我正在为JAX-RS前端使用RestEasy 1.2.1 GA。
UPDATE(安德鲁白色):这里是代码演示获取Class
对象类型参数(一个或多个):
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
public class TestReflection
extends AbstractCollection<String> {
public static void main(final String[] args) {
final TestReflection testReflection = new TestReflection();
final Class<?> cls = testReflection.getClass();
final Type[] types = ((ParameterizedType) cls.getGenericSuperclass()).getActualTypeArguments();
for (final Type t : types) {
final Class<?> typeVariable = (Class<?>) t;
System.out.println(typeVariable.getCanonicalName());
}
}
}
class AbstractCollection<T> {
protected List<T> collection = new ArrayList<T>();
}
这里是输出:java.lang.String
。
您不必在'@ XmlElement'上指定'name'属性,因此您可以将'@ XmlElement'添加到'AbstractCollection.collection'中,并让JAXB推断出元素名称。 – skaffman 2011-03-23 11:14:33
@skaffman:它不工作。我得到了一个'javax.xml.bind.JAXBException:class com.example.Person,但是它的任何超类都不知道这个上下文吗? – Ralph 2011-03-23 12:19:33
那么这是你创建JAXB上下文的错误。将其添加到您的问题中,我将发布答案。 – skaffman 2011-03-23 12:38:44