自定义IDResolver获取错误的目标类型

时间:2013-03-29 19:22:33

标签: java jaxb unmarshalling

ITNOA

我写了这个自定义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解析。 我的问题在哪里?

非常感谢

1 个答案:

答案 0 :(得分:0)

当部门包含课程时,您不应使用IDResolve。当部门想要引用课程时应该使用它。因此,当jaxb到达某个部门内部的一个课程时,它包含一个元素(听到),它会将object.class传递给你的解析函数。