0

我写了这个自定义 IDResolver:

final class MyIDResolver extends IDResolver {

    Map<String, Course> courses = new HashMap<>();

    /**
     * @see com.sun.xml.bind.IDResolver#bind(java.lang.String, java.lang.Object)
     */
    @Override
    public void bind(String id, Object obj) throws SAXException {
        if (obj instanceof Course)
            courses.put(id, (Course)obj);
        else
            throw new SAXException("This " + obj.toString() + " cannot found");
    }

    /**
     * @see com.sun.xml.bind.IDResolver#resolve(java.lang.String, java.lang.Class)
     */
    @Override
    public Callable<?> resolve(final String id, final Class targetType) throws SAXException {
        return new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                if (targetType == Course.class)
                    return courses.get(id);
                else
                    throw new ClassNotFoundException(targetType.toString() + " cannot found");
            }
        };
    }
 }

我有两个课程,例如:

@XmlRootElement(name = "course")
public class Course {
    @XmlID
    @XmlAttribute
    private String id;

    @XmlAttribute
    private int units;

    @XmlAttribute
    private Level level;

    @XmlAttribute
    private String name;

    @XmlIDREF
    @XmlElement(name = "pre")
    private ArrayList<Course> prerequisite;

    @XmlIDREF
    @XmlElement(name = "co")
    private ArrayList<Course> corequisite;
}

@XmlRootElement(name = "dept")
@XmlAccessorType(XmlAccessType.FIELD)
public final class Department {
    @XmlAttribute
    private String name;

    @XmlElementWrapper(name = "courses")
    @XmlElement(name = "course")
    private ArrayList<Course> courses;
}

像这样的示例 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<dept name="ece">
    <courses>
    <course id="1" units="4" level="UNDERGRADUATE" name="Fundamentals of Programming"/>
    <course id="2" units="3" level="UNDERGRADUATE" name="Advanced Programming">
        <pre>1</pre>
    </course>
    </courses>
</dept>

还有一个像这样的简单主要内容:

unmarshaller.unmarshal(new FileReader(arg0))
context = JAXBContext.newInstance(Department.class);
unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(IDResolver.class.getName(), new MyIDResolver());

自定义 IDResolver 的 resolve() 方法将 Object.class 作为 targetType。但它应该是 Course.class。这会导致错误的 ID 解析。我的问题在哪里?

4

1 回答 1

0

当 Department 包含课程时,您不应使用 IDResolve。当部门想要参考课程时,应该使用它。因此,由于这个原因,当 jaxb 到达一个部门内部的课程时,它包含一个元素(此处为 <pre>),它会将object.class传递给您的 resolve 函数。

于 2013-03-30T17:17:01.367 回答