[英]Java referencing class from another
我有以下兩類動物和動物園,
動物類
public class Animal {
private int id;
private String name;
private String animal_order;
private String family;
private String genus;
private String species;
private int number_avilable;
private Zoo _zoo;
public Animal() {
}
public Animal(ArrayList<Animal> allAnimals) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Animal (int id, String name, String animal_order, String family, String genus, String species,int number_avilable, Zoo _zoo){
this.id = id;
this.name = name;
this.animal_order = animal_order;
this.family = family;
this.genus = genus;
this.species = species;
//this.zoo = zoo;
this.number_avilable = number_avilable;
this._zoo = _zoo;
}
}
動物園班
public class Zoo {
private String zoo_name;
private String link;
private String lat;
private String lng;
private String postcode;
private String image;
public Zoo() {
}
public Zoo(ArrayList<Zoo> allZoos) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Zoo (String zoo_name, String link,String postcode, String image){
this.zoo_name = zoo_name;
this.link = link;
//this.lat = lat;
//this.lng = lng;
this.postcode = postcode;
this.image = image;
}
}
正如您從我的代碼中看到的那樣,我嘗試在Animal中引用Zoo類。 我在Animal類中有以下方法,
public static ArrayList<Animal> getAllAnimals() throws Exception {
PreparedStatement query = null;
Connection conn = null;
ArrayList<Animal> results = new ArrayList();
try {
// connect to database
conn = Database.mySqlDBConn().getConnection();
// run a query
query = conn.prepareStatement("{CALL get_animal()}");
ResultSet rs = query.executeQuery();
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String animal_order = rs.getString("animal_order");
String family = rs.getString("family");
String genus = rs.getString("genus");
String species = rs.getString("species");
int number_avilable= rs.getInt("number_avilable");
String zoo_name = rs.getString("zoo_name");
String link = rs.getString("link");
String postcode = rs.getString("postcode");
String image = rs.getString("image");
Zoo _zoo = new Zoo(zoo_name, link, postcode, image);
Animal animal = new Animal(id, name,animal_order,family, genus, species,number_avilable, _zoo);
results.add(animal);
}
}
}
上面的方法應該返回一個既包含動物又包含動物園的數組列表,但此刻它僅返回動物而不是動物園信息。 我一直在通過堆棧溢出來獲取類參考和內容,但無法找出線索。
僅供參考,我的存儲過程工作正常。
您想要同時包含動物和動物園的ArrayList嗎? 看起來您只是將動物添加到了數組列表中,並且將動物園添加到了動物中,因此,如果要獲取動物園,只需在Animal類中添加一個吸氣劑即可:
public Zoo getZoo() {
return _zoo;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.