【问题标题】:Object attribute returns as null [closed]对象属性返回为 null [关闭]
【发布时间】:2022-01-22 23:59:24
【问题描述】:

[已解决] 好吧,我两次初始化附件属性是愚蠢的。感谢 user16320675 找到这个!

这是我在这里的第一篇文章,所以如果我犯了一些正式的错误,请放轻松。我的问题是,Customer 类的属性返回 null,尽管事实上它将由 Customer 类本身的构造函数创建。我不明白这怎么可能,它应该在那里。也许你能帮助我理解。

这是 Customer 类,创建后应该有一个 Attachement 类型的属性。

package model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Customer {

private String name;
private String projectNr;
private String[] aliases;
private String[] blocks;
private Attachment attachement;

public Customer(String name, String projectNr, String[] aliases, String[] blocks, ArrayList<TransactionFile> allFiles) {
    super();
    this.name = name;
    this.projectNr = projectNr;
    this.aliases = aliases;
    this.blocks = blocks;
    this.attachement = new Attachment(this, allFiles);

}

@Override
public String toString() {
    return "Customer [name=" + name + ", projectNr=" + projectNr + ", aliases=" + Arrays.toString(aliases)
            + ", blocks=" + Arrays.toString(blocks) + "]";
}

public Attachment getAttachement() {
    return attachement;
}

public void setAttachement(Attachment attachement) {
    this.attachement = attachement;
}

public String[] getAliases() {
    return aliases;
}

public void setAliases(String[] aliases) {
    this.aliases = aliases;
}

private Attachment attachment;

public String getProjectNr() {
    return projectNr;
}

public void setProjectNr(String projectNr) {
    this.projectNr = projectNr;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String[] getBlocks() {
    return blocks;
}

public void setBlocks(String[] blocks) {
    this.blocks = blocks;
}

public Attachment getAttachment() {
    return attachment;
}

public void setAttachment(Attachment attachment) {
    this.attachment = attachment;
}

}

这是附件类。在一些尝试中,我在构造函数的末尾使用了一个 sysout,表示该对象已构建。

    package model;

import java.util.ArrayList;

import controller.AttachmentBuilder;

public class Attachment{

private Customer customer;
private ArrayList<FixedPosition> fixedPositions;
private ArrayList<TransactionFile> transactionFiles;

public Attachment(Customer customer, ArrayList<TransactionFile> allFiles) {
    super();
    this.customer = customer;
    this.fixedPositions = null;
    this.transactionFiles = new AttachmentBuilder(allFiles).createTransactionList(this.customer);
    
}

@Override
public String toString() {
    return "Attachment [customer=" + customer + ", fixedPositions=" + fixedPositions + ", transactionFiles="
            + transactionFiles + "]";
}

public Customer getCustomer() {
    return customer;
}

public void setCustomer(Customer customer) {
    this.customer = customer;
}

public ArrayList<FixedPosition> getFixedPositions() {
    return fixedPositions;
}

public void setFixedPositions(ArrayList<FixedPosition> fixedPositions) {
    this.fixedPositions = fixedPositions;
}

public ArrayList<TransactionFile> getTransactionFiles() {
    return transactionFiles;
}

public void setTransactionFiles(ArrayList<TransactionFile> transactionFiles) {
    this.transactionFiles = transactionFiles;
}


}

当我在创建我的客户数组后运行这部分时,我会为 customer.getAttachement() 获得空值。作为记录,它有一个 toString()。

package controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.sql.Timestamp;
import java.util.ArrayList;


import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import model.Customer;
import model.TransactionFile;

public class Application {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    
    
    SshConnector sshConnector = new SshConnector();
    sshConnector.openSession();
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    Date date = new Date(ts.getTime());
    System.out.println(date);
    
    AttachmentBuilder ab = new AttachmentBuilder(sshConnector.getTransactions("2109"));
    ab.serializeFiles(sshConnector.getFolder());        
    sshConnector.closeSession();
    ts = new Timestamp(System.currentTimeMillis());
    date = new Date(ts.getTime());
    System.out.println(date);
    
    // build the customers
    String fileContent="";
    ArrayList<Customer> customerList = new ArrayList<>(); 
    
    File file = new File("src/resources/customer.json");
    try {
        fileContent = FileUtils.readFileToString(file, "utf-8");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    System.out.println("Baue JSON array");
    JSONArray customerArray = new JSONArray(fileContent);
    
    for (int i = 0; i < customerArray.length(); i++) {
        JSONObject tmpJsonObject = customerArray.getJSONObject(i);
        JSONArray tmpAliases = tmpJsonObject.getJSONArray("aliases");
        String aliases [] = new String [tmpAliases.length()];
        for(int j=0; j<tmpAliases.length(); j++) {
            aliases[j] = tmpAliases.getString(j);           
        }
        JSONArray tmpBlocks = tmpJsonObject.getJSONArray("blocks");
        String blocks [] = new String [tmpBlocks.length()];
        for(int j=0; j<tmpBlocks.length(); j++) {
            blocks[j] = tmpBlocks.getString(j);         
        }
        
        customerList.add(new Customer(tmpJsonObject.getString("name"), tmpJsonObject.getString("projectNr"),aliases, blocks, ab.getAllFiles()));
    }
    System.out.println("gebe customer aus");
    for (Customer customer : customerList) {
        System.out.println(customer);
        System.out.println(customer.getAttachment());
    }
    
    System.exit(0);

这是附件生成器

    package controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import model.Customer;

import model.TransactionFile;

public class AttachmentBuilder {

private  ArrayList<TransactionFile> allFiles;

public AttachmentBuilder(ArrayList<TransactionFile> allFiles) {
    super();
    this.allFiles = allFiles;
}

public ArrayList<TransactionFile> getAllFiles() {
    return allFiles;
}

public void setAllFiles(ArrayList<TransactionFile> allFiles) {
    this.allFiles = allFiles;
}

/*
 * writes the objects from the ArrayList that holds the transactions into a txt
 * file only for testing purpose
 * 
 * @Param ArrayList containing the files to serialize
 * 
 * @Param String substring to complete the file name usualy the folder that had
 * the actual month
 */
public void serializeFiles(String folder) {
    try {
        File fakturaRaw = new File("faktura" + folder + ".txt");
        System.out.println("Schreibe File");
        FileWriter writer = new FileWriter(fakturaRaw);
        for (TransactionFile transactionFile : allFiles) {
            writer.write(transactionFile.toString() + System.lineSeparator());
        }
        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public ArrayList<TransactionFile> createTransactionList(Customer customer) {
    ArrayList<TransactionFile> list = new ArrayList<TransactionFile>();

    if (customer.getBlocks() != null) {

    } else {
        for (int i = 0; i < this.allFiles.size(); i++) {
            
            for (int j = 0; j < customer.getAliases().length; j++) {
                
                if (this.allFiles.get(i).getFileName().contains(customer.getAliases()[j])) {
                    list.add(allFiles.get(i));
                }
            }
        }
    }

    return list;
}

}

    

【问题讨论】:

  • 您能展示创建(customerList 的)客户实例的代码吗?
  • customerList 是如何/在哪里定义的? getAttachment 是如何/在哪里定义的?请提供一个minimal reproducible example 来说明问题。
  • 问题不在您显示的代码中,所以它必须在其他地方......
  • 我已经编辑了操作并确实放入了所有涉及的代码
  • 您能分享一下您是如何启动 customerList 实例并在类中覆盖 toString 方法的吗?分享minimal, reproducible example 很重要。谢谢。

标签: java oop


【解决方案1】:

为了在java中使用super你需要继承一个类,我猜你想要做的是扩展客户类,所以你需要改变类

public class Attachment

public class Attachment extends Costumer

然后你需要像这样使用 super() 来调用 Attachment 类中的复制构造函数:

super(customer);

添加客户对象将告诉编译器选择复制构造函数。 这将是你的情况:

public Customer(Customer other) {
    //deep copy
 }

最后你不需要在 Customer 类中声明一个 Attachment 对象。

【讨论】:

  • 为什么你认为Attachment应该是Customer的子类?
  • 不,它不是客户的孩子。 Attachemt 是 Customer 的一个属性
  • 如果是属性为什么还要使用 super?
  • @user16320675 我知道,但我不认为他想这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多