我是Java的新手,所以我想知道是否有可能这样做?
我有一个文档对象,说是文档doc1 ..一旦我使用jdom构建器来构建该对象,我就不希望对其进行更改..它也必须始终可用..我相信后者可以使用static关键字..如何确保一旦使用jdom构建器,没人能修改该对象?因此,在下面的内容中,该类中的声明应该是什么,以确保一旦我使用builder ..构建后,templateDocument就不能被修改。

public static void createDocumentFromTemplate(StatusBuffer statusBuffer)
{
    //templateDocument = new Document();
    SAXBuilder builder = new SAXBuilder();
    Reader input = new StringReader(statusBuffer.toString());
    try {
        templateDocument = builder.build(input);
    } catch (JDOMException e) {
        final String message = "Error in building xml from output template";
        LOG.error(message, e);

    } catch (IOException e) {
        final String message = "Error in accessing output file template";
        LOG.error(message, e);

    }

最佳答案

您可以声明templateDocument final,这将防止任何人重新分配引用。但是,这不会阻止他们设置templateDocument的成员字段。因此,如果templateDocument具有您之前分配的某个成员字段,并且为该字段定义了公共设置器,则仍可以重新分配该字段。

08-06 17:24