JAXB 解组返回 Null

2023-12-25

我正在制作这个示例 GUI,它只是将计算机部件从一侧移动到另一侧,并且能够将列表(以 xml 格式)加载和保存到桌面。除了重新加载已保存的 xml 文件之外,一切正常。我认为这与Save.java中的注释有关。话虽如此,我不确定需要什么或者这是否是问题所在。任何帮助将不胜感激。

窗口.java

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.ListSelectionModel;

import java.awt.Component;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.BoxLayout;
import javax.swing.JList;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

public class Window {

    private JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Window() {
        initialize();
    }

    public void addTo(JPanel displayPanel, Component contentToAdd)
    {
        displayPanel.add(contentToAdd);
    }

    public void initialize() {

        //setting the dimension for the JList panels
        Dimension sidePanelSize = new Dimension(180, 540);

        frame = new JFrame();
        frame.setBounds(100, 100, 480, 540);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Creating the menu bar 
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        //adding File option to menu bar
        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        //adding load option to File
        JMenuItem mntmLoad = new JMenuItem("Load");
        mnFile.add(mntmLoad);

        //adding save option to File
        JMenuItem mntmSave = new JMenuItem("Save");
        mnFile.add(mntmSave);

        //adding exit option to File
        JMenuItem mntmExit = new JMenuItem("Exit");
        mnFile.add(mntmExit);

        //creating Jpanel that will hold JList for computer parts 
        //that you can choose 
        final JPanel itemPanel = new JPanel();
        itemPanel.setPreferredSize(sidePanelSize);
        itemPanel.setBackground(Color.WHITE);
        itemPanel.setLayout(new BorderLayout());

        //Create the model that will hold the computer items
        //For loop to add the strings to the model
        DefaultListModel<String> model = new DefaultListModel<>();
        for (String items : new String [] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"})
            model.addElement(items);
        //Create JList(itemList) and set its model to the one 
        //holding the computer parts
        final JList<String> itemList = new JList<>(model);

        //Setting attributes for the JList(itemList) - font, Number of elements you can select at a time
        itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        itemList.setFont(new Font("SegoeUI", Font.BOLD, 11));
        //adding the JList to the Panel
        itemPanel.add(itemList, BorderLayout.WEST);
        //adding the Panel to the frame
        frame.getContentPane().add(itemPanel, BorderLayout.WEST);

        //creating two panels that are used for centering the JList buttons
        JPanel buttonContainer = new JPanel();
        JPanel buttonList = new JPanel();
        GridBagConstraints c = new GridBagConstraints();

        //setting the layout managers for the panels and 
        //adding color to the background
        buttonList.setLayout(new BoxLayout(buttonList, BoxLayout.Y_AXIS));
        buttonContainer.setLayout(new GridBagLayout());
        buttonContainer.setBackground(new Color(238, 238, 238));

        //adding the button to add content from Jlist on the left(itemList)
        //to the right JList(addToList)
        JButton addButton = new JButton(">>");
        buttonList.add(addButton);

        //adding the button to remove content form the JList(addToList)
        JButton deleteButton = new JButton("<<");
        buttonList.add(deleteButton);

        //setting where to start inputing element into the
        //grid of the ButtonContainer
        c.gridx = 0;
        c.gridy = 0;

        //adding the button panel container and its constraints 
        //to the main container
        //finally adding it all to the main frame
        buttonContainer.add(buttonList, c);
        frame.getContentPane().add(buttonContainer, BorderLayout.CENTER);

        //creating the JList that we will add and remove from
        final JList<String> addToList = new JList<>(new DefaultListModel<String>());

        //creating the panel to hold the JList(addToList)
        //setting its size and layout in the manager
        //finally adding it to the main frame
        final JPanel displayPanel = new JPanel();
        displayPanel.setPreferredSize(sidePanelSize);
        displayPanel.setBackground(Color.WHITE);
        displayPanel.add(addToList, BorderLayout.EAST);
        frame.getContentPane().add(displayPanel, BorderLayout.EAST);    



        //Here is all the action listeners for button click events and menu events
        //contains all the methods for the action events
        final ActionListeners b = new ActionListeners();

        //Listener that adds selected computer parts from left JList(itemList) to the right JList(addToList)
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                b.addContent(itemList, addToList);
            }
        });

        //Listener that removes selected computer part from the JList(addToList) 
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                b.removeContent(addToList);
            }
        });

        //Listener that calls the save methods to save JList(addToList) content into xml
        mntmSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                b.saveContent((DefaultListModel<String>) addToList.getModel());
            }
        });

        //Listener that call the load methods to load xml into the JList(addToList)
        mntmLoad.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                b.loadContent(addToList);
            }
        });

        //Exits the program entirely 
        mntmExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                b.exitProgram();
            }
        });
    }
}

加载.java

import java.io.File;

import javax.swing.DefaultListModel;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;


public class Load {
    //loads the file into the JList to be displayed in the program
    public DefaultListModel<String> loadXMLFile() {
        //array that holds the content from the xml file

        //model that will have xml file's content added to it 
        //from the array
        DefaultListModel<String> modelToReturn = new DefaultListModel<>();
        String[] partsList = null;

        try {
            String homeDir = System.getProperty("user.home");
            File file = new File(homeDir + "/Desktop/xml.xml");

            JAXBContext jaxbContext = JAXBContext.newInstance(Save.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

            Save load = (Save) jaxbUnmarshaller.unmarshal(file);
            partsList = new String [load.getPartsList().length];

          } catch (JAXBException e) {
            e.printStackTrace();
          }

        //adds the strings in the arrayToReturn
        //to the model that will be returned
        for(int i = 0; i < partsList.length; i++)
        {
            modelToReturn.addElement(partsList[i]);
        }

        return modelToReturn;
    }
}

ActionListeners.java

import java.io.File;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ActionListeners {

    public void addContent(JList<String> itemList, JList<String> addToList)
    {
        //gets the value selected to be added to other other JList
        List<String> selected = itemList.getSelectedValuesList();
        //gets the model of the List to be added too
        DefaultListModel<String> displayModel = (DefaultListModel<String>) addToList.getModel();

        //adds the elements to the JList
        for (String item: selected) 
        {
            displayModel.addElement(item);
        }
    }

    public void removeContent(JList<String> addToList)
    {
        //gets the element selected to be removed
        List<String> selected = addToList.getSelectedValuesList();
        //gets the model of the JList where content will be removed
        DefaultListModel<String> displayModel = (DefaultListModel<String>) addToList.getModel();

        //removes the selected element
        for (String item: selected) {
            displayModel.removeElement(item);
        }
    }

    public void saveContent(DefaultListModel<String> addToList)
    {
        Save saveFile = new Save();
        //adds the content in the JList to be saved
        //to the object
        saveFile.setPartsList(addToList);

        try {
            JAXBContext jaxbContext = 
                    JAXBContext.newInstance(Save.class);
            Marshaller jaxbMarshaller = 
                    jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            String homeDir = System.getProperty("user.home");

            jaxbMarshaller.marshal(saveFile, new File(homeDir + "/Desktop", "xml.xml"));

            jaxbMarshaller.marshal(saveFile, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }

        //saves the content
        //saveFile.saveFileXml();
    }

    public void loadContent(JList<String> addToList)
    {
        Load loadFile = new Load();
        //gets the model of the JList that loaded content will be added too
        DefaultListModel<String> newModel= (DefaultListModel<String>) addToList.getModel();
        //makes sure the model is clear
        newModel.removeAllElements();
        //makes model that the loaded content will be set too
        DefaultListModel<String> loadedModel = loadFile.loadXMLFile();

        //adds the loaded elements from the file to JList's model
        for(int i = 0; i < loadedModel.getSize(); i++)
        {
            newModel.addElement(loadedModel.get(i));
        }
    }

    public void exitProgram()
    {
        //closes the entire program
        System.exit(0);
    }
}

保存.java

import javax.swing.DefaultListModel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement (name = "lists")
public class Save {
    //array that will hold the content to be saved
    String[] partsListSave;

    //method to set the array partsListSave
    //with the content that will be saved
     public void setPartsList(DefaultListModel<String> model) {
         //Initialize the array with the length of the content
         //to be added
         partsListSave = new String[model.getSize()];

         //adds the content to the array
         for (int i = 0; i < model.getSize(); i++)
         {
             partsListSave[i] = model.getElementAt(i);
         }
     } 

    @XmlElement (name = "parts")
    public String[] getPartsList() {
        return partsListSave;
    }
}

xml.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lists>
    <parts>Motherboard</parts>
    <parts>Motherboard</parts>
    <parts>Motherboard</parts>
    <parts>Motherboard</parts>
</lists>

Your Save.java类需要一个适当的 setter 方法:

public void setPartsList(String[] partsListSave) {
    this.partsListSave = partsListSave;
}

为了验证这一点,我创建了文件xml.xml:

<lists>
    <parts>Part 1</parts>
    <parts>Part 2</parts>
    <parts>Part 3</parts>
</lists>

和一个测试类:

public static void main(String[] args) throws Exception {
    File file = new File("xml.xml");

    JAXBContext jaxbContext = JAXBContext.newInstance(Save.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Save load = (Save) jaxbUnmarshaller.unmarshal(file);

    for (String parts : load.getPartsList())
        System.out.println(parts);
}

和你的Save.java,它因 NPE 失败。添加设置器有效。

最小、完整且可验证.


Note

你的问题部分是基于误解。

JAXB 解组器(调用jaxbUnmarshaller.unmarshal(file);) does not return null- 它返回一个实例Save, 正如它应该。unmarshal()本身永远不会回来null (see API 文档Unmarshaller https://docs.oracle.com/javaee/7/api/javax/xml/bind/Unmarshaller.html:“解组方法永远不会返回 null。”) - 但是它返回的实例中的字段可能是null.

在这种情况下,字段Save.partsListSave is null,因为 JAXB 无法设置它,因为没有适当的设置器,如上所述。

您看到的 NullPointerException 是由于尝试使用返回的值引起的getPartsList(),即null.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JAXB 解组返回 Null 的相关文章

  • 使用cameltestsupport进行Camel单元测试,模板始终为空

    我正在用 Camel 做一个简单的单元测试 我想做的就是从文件 在资源下 读取 JSON 内容 将其发送到 Java 类进行验证 这是我试图测试的路线 无论我做什么 模板 我用来发送正文 json 始终为空 这是我的代码 public cl
  • 如何从 MySQL 数据查询创建 XML 文件?

    我想知道一种仅使用 MySQL 查询创建 XML 文件的方法 根本不使用任何脚本语言 有关于这个主题的书籍 教程吗 UPDATE 我想澄清一下 我想使用 sql 查询将 XML 数据转发到 php 脚本 Here s 关于从 MySQL S
  • 使用 xmllint 检查 XML 语法

    我在处理某些 XML 打印文件时遇到问题 其中源系统忽略将某些字符转换为其等效的 XML 语法 例如 未转换为 amp 有没有办法用 xmllint 捕获这个 我不需要使用 XSD 检查一般树结构 xmllint noout your te
  • 如何从秘密字符串中制作 HMAC_SHA256 密钥以在 jose4j 中与 JWT 一起使用?

    我想生成 JWT 并使用 HMAC SHA256 对其进行签名 对于该任务我必须使用jose4j https bitbucket org b c jose4j wiki Home 我尝试根据秘密生成密钥 SecretKeySpec key
  • Spring安全“记住我”cookie在第一个请求中不可用

    我无法在登录请求后检索 Spring 记住我 cookie 但它在对受保护页面的下一个请求中工作正常 谁能告诉我怎样才能立即得到它 我在登录请求中设置了记住我的 cookie 但在 Spring 重定向回原始 受保护的 url 后无法检索它
  • 在文本文件中搜索单词并返回其频率

    如何在包含单词文本的文本文件中搜索特定单词并返回其频率或出现次数 使用扫描仪 String text Question how to search for a particular word in a text file containin
  • 如何在 JSP 中导入类?

    我是一个完全的JSP初学者 我正在尝试使用java util List在 JSP 页面中 我需要做什么才能使用除以下类之外的类java lang 使用以下导入语句进行导入java util List 顺便说一句 要导入多个类 请使用以下格式
  • Firestore - RecycleView - 图像持有者

    我不知道如何编写图像的支架 我已经设置了 2 个文本 但我不知道图像的支架应该是什么样子 你能帮我告诉我图像的文字应该是什么样子才能正确显示吗 holder artistImage setImageResource model getArt
  • 如何在android中设置多个闹钟,在这种情况下最后一个闹钟会覆盖以前的闹钟

    我正在开发一个Android应用程序 用户可以在其中设置提醒时间 但我在以下代码中遇到一个问题 即最后一个警报会覆盖之前的所有警报 MainActivity java public void setreminders DatabaseHan
  • Git 无法识别重命名和修改的包文件

    我有一个名为的java文件package old myfile java 我已经通过 git 提交了这个文件 然后我将我的包重命名为new所以我的文件在package new myfile java 我现在想将此文件重命名 和内容更改 提交
  • Ebay api GetSellerList,解析响应 XML

    我正在使用 eBay 交易 api 来获取当前列出的卖家股票 我正在使用 GetSellerList 调用 我在解析 xml 时遇到问题 然后将其插入到网站商店中 这是 xml 请求
  • 在 Spring Boot Actuator 健康检查 API 中启用日志记录

    我正在使用 Spring boot Actuator APIproject https imobilenumbertracker com 拥有一个健康检查端点 并通过以下方式启用它 management endpoints web base
  • 如何配置 WebService 返回 ArrayList 而不是 Array?

    我有一个在 jax ws 上实现的 java Web 服务 此 Web 服务返回用户的通用列表 它运行得很好 Stateless name AdminToolSessionEJB RemoteBinding jndiBinding Admi
  • Espresso 和 Proguard 的 Java.lang.NoClassDefFoundError

    我对 Espresso 不太有经验 但我终于成功地运行了它 我有一个应用程序需要通过 Proguard 缩小才能处于 56K 方法之下 该应用程序以 3 秒的动画开始 因此我需要等到该动画结束才能继续 这就是我尝试用该方法做的事情waitF
  • 将图像添加到自定义 AlertDialog

    我制作了一个 AlertDialog 让用户可以从我显示的 4 个选项中选择一个 前 3 个让他们在单击号码时直接拨打号码 第 4 个显示不同的视图 现在看起来是这样的 由于第四个选项的目的是不同的任务 我想让它看起来不同 因为用户可能会感
  • 解决错误javax.mail.AuthenticationFailedException

    我不熟悉java中发送邮件的这个功能 我在发送电子邮件重置密码时遇到错误 希望你能给我一个解决方案 下面是我的代码 public synchronized static boolean sendMailAdvance String emai
  • Java:多线程内的 XA 事务传播

    我如何使用事务管理器 例如Bitronix http docs codehaus org display BTM Home JBoss TS http www jboss org jbosstm or Atomikos http www a
  • 在android中跟踪FTP上传数据?

    我有一个运行 Android 的 FTP 系统 但我希望能够在上传时跟踪字节 这样我就可以在上传过程中更新进度条 安卓可以实现这个功能吗 现在 我正在使用org apache common net ftp我正在使用的代码如下 另外 我在 A
  • JAXB - 列表<可序列化>?

    我使用 xjc 制作了一些课程 public class MyType XmlElementRefs XmlElementRef name MyInnerType type JAXBElement class required false
  • 在哪里存储 Java 的 .properties 文件?

    The Java教程 http download oracle com javase tutorial essential environment properties htmlon using Properties 讨论如何使用 Prop

随机推荐

  • Python错误:找不到指定的文件

    这是我的代码主体 os chdir C Users Desktop rc subprocess call 7z a test y myarchive zip r device teams txt 它给我一个指向 r deviceteams
  • 带有 ffmpeg 的 svg 幻灯片[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 谁能向我指出如何使用 svg 图像制作幻灯片 使用 ffmpeg 通常的方式 ffmpeg i bloch 0 2d svg bloch2 mp4 不
  • 使用 Excel VBA 填写并提交 Google 文档表单

    我正在尝试做类似的事情这个帖子 https stackoverflow com questions 2128367 scripting a google docs form submission但使用 Excel VBA 每次在 Excel
  • 如何在 Weblogic 响应中配置 HTTP 标头

    使用 WebLogic 11g 并希望能够向 WebLogic 提供的所有文件添加标头 WebLogic 前面没有单独的 Web 服务器 找不到配置 WebLogic 向 HTTP 响应添加标头的方法 在 IIS 中 您可以通过选择服务器并
  • 多少 GCHandle 固定内存/对象会使垃圾收集器变慢?

    我确信这个答案取决于用户机器 但一定有一些固定数据的最佳实践 我需要保存 5 个字节数组 每个数组包含 1 048 576 字节 通常我更喜欢使用GCHandle 托管 内存 但有些人说这会减慢 GC 的速度 我知道这可能会发生 但是需要固
  • 是否无法将文件夹添加到 ASP.NET bin 文件夹?

    因为我试图重新创建一个遗留的 ASP NET 项目 而不是继续陷入兔子洞 试图弄清楚为什么它给了我一个关于它在哪里的线索 未设置对象引用 https stackoverflow com questions 40875865 why am i
  • 如何检查某个元素在屏幕上是否完全可见?

    我在 OS X 上使用 Selenium WebDriver 和 Chrome 驱动程序 用 Python 实现 我正在尝试编写一个测试来验证各种 HTML 元素是否完全地在屏幕上 例如 我有一个标签云 由于我的实现不佳 有时有些单词会从浏
  • Python - 如何从类方法中获取类名 - 使用@classmethod

    我有以下代码 class ObjectOne object classmethod def print class name cls print cls class name def print class name again self
  • GWT 列表框 - 如何使用文本查找项目索引?

    无论如何 是否可以使用 GWT 列表框中的项目文本查找项目的索引号 不 你必须通过它们并自己找到该索引 像这样 String text listBoxText int indexToFind 1 for int i 0 i
  • 使用正则表达式避免 pandas str.replace

    我有以下熊猫数据框 假设它有两列 id and search term id search term 37651 inline switch I do train search term train search term str repl
  • 如何从 flutter 访问设备应用

    有没有办法从 flutter 应用程序访问设备中安装的应用程序的详细信息并访问其隐私权限详细信息 例如 GMAIL 在我们的设备中拥有多少访问权限 目前没有官方库可用于检索设备中安装的软件包 你可以查看非官方插件 包管理器插件 https
  • 在视图寻呼机上方显示具有嵌套片段的对话框

    我设置了一个非常简单的测试项目https github com ArtworkAD ViewPagerDialogTest https github com ArtworkAD ViewPagerDialogTest评估以下情况 主要活动有
  • 为什么SSIS运行时无法启动分布式事务?

    在为 SQL Server 2008 创建 SSIS 包时 我遇到以下错误 错误 SSIS 运行时未能 启动分布式事务到期 错误 0x8004D01B 交易 经理没空 DTC 交易未能开始 这 可能会发生 因为 MSDTC 服务 没有运行
  • Java的Paint方法存在问题,刷新速度太离谱

    我正在为大学开发一个非常简单的 R Type 版本 但尽管它有效 但飞行速度却很慢 所以动作丑陋且笨拙 我使用重绘方法来刷新屏幕 还有其他方法或比它更好的方法吗 主面板的绘制方法 Override public void paint Gra
  • Rails:在初始化程序中获取主机名

    我正在使用 Sorcery 进行身份验证 并且需要在其初始值设定项中设置第三方身份验证 初始化程序有一行如下所示 config twitter callback url http example dev auth callback prov
  • Appengine 批量下载器未下载列表属性

    这与我之前的一个问题 https stackoverflow com questions 4231153 appengine bulkdownloader to xml with nested entities 但有新信息 我正在尝试将bu
  • 冷融合映射错误

    注意 如果您想使用绝对模板路径 例如 template mypath index cfm 与 CFINCLUDE 您必须创建一个 使用 ColdFusion Administrator 映射路径 我进入了管理页面 但不知道要在这里输入什么
  • fieldset 必须是表单吗?

    我对DTD一无所知 http www bls gov oco ocos292 htm http www bls gov oco ocos292 htm 在此页面上查看如何在表单之外使用 fieldset 这很酷 我喜欢这种风格 我认为这个问
  • 在 React 中将数据从子级传递给父级

    我在 React 中有 3 个组件 其中一个充当容器 将我的子组件传递到表单中进行渲染 提交表单时 我想获取父组件中的每个子组件 循环遍历每个子组件 创建服务器期望的对象 然后将对象列表发送回服务器 我正在努力访问父组件中 onSubmit
  • JAXB 解组返回 Null

    我正在制作这个示例 GUI 它只是将计算机部件从一侧移动到另一侧 并且能够将列表 以 xml 格式 加载和保存到桌面 除了重新加载已保存的 xml 文件之外 一切正常 我认为这与Save java中的注释有关 话虽如此 我不确定需要什么或者