有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java构造函数来分配整个类,而不仅仅是字段

我的系统是jibx和一个遗留xml应用程序,我想构建一个构造函数,它可以接受xml字符串并将其解组到自己的类中。像这样:

public ActiveBankTO(String xmlIn)
    {
        try
        {
            ByteArrayInputStream bin = new ByteArrayInputStream(xmlIn.getBytes());
            IBindingFactory bfact;
            bfact = BindingDirectory.getFactory(ActiveBankTO.class);
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
            this = (ActiveBankTO) uctx.unmarshalDocument(bin, null);
        } catch (JiBXException e)
        {
            e.printStackTrace();
        }
    }

但很明显,我不能将“this”指定为变量。有没有办法让这一切顺利进行?我意识到我可以把它放在一个可以使用的静态方法中,或者用一些其他的技巧来让它工作,但这是一些以各种形式出现在几个项目中的东西,我想知道这种特殊的方法是否可行


共 (2) 个答案

  1. # 1 楼答案

    不,在构造器中是不可能的。静态工厂方法是唯一真正的方法(在字节码中你甚至不能像这样作弊)

  2. # 2 楼答案

    不,不可能。静态方法是最好的解决方案

    public static ActiveBankTO parseActiveBankTO(String xmlIn) {
        ActiveBankTO newTO = null;
        try {
            ByteArrayInputStream bin = new ByteArrayInputStream(xmlIn.getBytes());
            IBindingFactory bfact;
            bfact = BindingDirectory.getFactory(ActiveBankTO.class);
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
            newTO = (ActiveBankTO) uctx.unmarshalDocument(bin, null);
        } catch (JiBXException e) {
            e.printStackTrace();
        }
        return newTO;
    }