【问题标题】:Getting the same reference variable to an object in other class java获取其他类java中对象的相同引用变量
【发布时间】:2014-07-19 20:32:21
【问题描述】:

我问的原因是我得到空指针异常。我有一个名为 SRSI.java 的类,它将解析图像转换为字节数组,我将这个字节数组存储到另一个类 Account 的 setter 方法中。现在我想要在另一个第三类中使用这个 setter 值让我们在 getter 方法的帮助下在动作类中说。但我得到了 NPE。 //下面是SRSI类的代码,我正在处理并存储到db中,同时我正在存储到setter方法中

        String fromLocal ="D://1-123456.jpg";
        long accountId = account.getId();
        File file = new File(fromLocal);
        System.out.println("Length--> " + file.length());
        InputStream inputStream = null;
        byte[] bFile= null;
        byte[] imageData = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
            bFile = new byte[8192];
            int count;
            while((count = inputStream.read(bFile))> 0){
                baos.write(bFile, 0, count);
            }
            bFile = baos.toByteArray();
            if(bFile.length > 0){
                imageData = bFile;
            }
            baos.flush();
            inputStream.close();
        } catch (Exception ioe) {
            //throw ioe;
        }
        //storing the above byte array which contains image into account class setter method here account is reference of account class.
        account.setImageData(imageData);


       //here what account class getter and setter methods looks like
            private byte[] imageData;

           public void setImageData(byte[] imageData){
            if(null!=imageData){
                this.imageData = imageData;
            }
        }

          public byte[] getImageData(){
            return imageData;
          }
         Now what i need this same value in getter method in 3rd class i.e.Action.What i am doing is 
         Action action = new Action();
         action.getImageData();

我知道它会创建新对象以及它返回 NPE 的原因。但是我需要将相同的 setter 值放入 Action 类和 Action 类和 SRSI,Account 位于不同的包中。

提前致谢。

【问题讨论】:

    标签: java reference nullpointerexception initialization


    【解决方案1】:

    您可以将两个对象相互分配,这将使它们的所指对象彼此可见。

    ob = obj;

    【讨论】:

      【解决方案2】:

      您的代码有点伪,但如果我理解正确,您只需要类似

      action.setImageData(account.getImageData());
      

      【讨论】:

        【解决方案3】:

        问题是每个实例都有自己的字段。通过编码,这是您的第三堂课:

        Action action = new Action();
        action.getImageData();
        

        这不会为您提供对另一个实例的图像数据的引用。

        相反,您必须将原始 Action 对象传递给第 3 类,可能通过创建 setAction(Action action) 方法并将传递给它的 Action 对象保存在字段中,然后在需要时使用 action.getInageDara()

        【讨论】:

          猜你喜欢
          • 2013-04-06
          • 1970-01-01
          • 2016-07-15
          • 2017-11-08
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多