【问题标题】:How to pass Java objects from one class to another class如何将 Java 对象从一个类传递到另一个类
【发布时间】:2018-12-30 23:38:47
【问题描述】:

我有 3 个类,一个主类,一个产品类和一个数据库类。 我的问题是如何将产品类中的对象传递给数据库类并在其上运行方法。

products class

private int product_id;
private String product_name;
private Double product_price;

//getters and setters

public void contructObjects() {
//using JSoup to scrape data from the web and form objects in a loop here.
}


database class
//using hibernate

public void initialise () {
//code that configures connection and other stuff
}

public void addproduct() {
//starts connection to database
Products product = new Products();
product.contructOjects();  //database class runs method in products class, get objects and hold them here.
}

public void shutdown() {
//stops session
}


main class

Database database = new Database();
database.initialise();
database.addproduct(); //main class gets obejcts held in database class stores them in databse.
database.shutdown();

【问题讨论】:

    标签: java hibernate class object


    【解决方案1】:

    可以将 public void contructObjects() 从仅执行命令更改为将返回值的 public List<(Your Object Datatype)> contructObjects()

    public List<(Your Object Datatype)> contructObjects() {
       List<(Your Object Datatype)> listObject = new ArrayList<>();
       //using JSoup to scrape data from the web and form objects in a loop here.
       //insert data from web into list, listObject.add(data);
       return listObject;
    }
    

    然后在数据库类中可以获取产品列表对象的值并可以将其用于任何目的:

    public void addproduct() {
       Products product = new Products();
       List<(Your Object Datatype)> listObject = product.contructOjects();//may use listObject for any purpose 
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      相关资源
      最近更新 更多