如何将Java对象从一个类传递到另一类

时间:2018-12-30 23:38:48

标签: java hibernate class object

我有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();

1 个答案:

答案 0 :(得分:0)

可以将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 

}