在我的Spring mvc应用程序中,我有一个ManagePerson类,需要返回Person或MinimalPerson,
如何让它从getPersons()返回Person或MinimalPerson?
ManagePerson.java
public class ManagePerson {
private List<Person> persons;
public ManagePerson(List<Person> persons) {
this.persons = persons;
}
public List<Person> getPersons() {
return persons;
}
}
Person.java
public class Person implements Comparable<Person> {
private String name;
private Long id;
public Person(String name, Long id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
@Override
public int compareTo(Person o) {
if(this.getId() == null) {
return -1;
}
if(this.getName() != null && o.getName() == null) return -1;
if(this.getName() == null && o.getName() != null) return 1;
if(!this.getName().equalsIgnoreCase(o.getName())) {
return this.getName().compareToIgnoreCase(o.getName());
}
return 0;
}
}
MinimalPerson.java
public class MinimalPerson() {
private Person person;
public MinimalPerson(Person person) {
this.person = person;
}
public String getName() {
return this.person.getName();
}
}
答案 0 :(得分:1)
让Person Extend MinimalPerson然后你的ManagePerson类必须是:
public class ManagePerson<T extends MinimalPerson> {
private List<T> persons;
public ManagePerson(List<T> persons) {
this.persons = persons;
}
public List<T> getPersons() {
return persons;
}
}
这使用了Java的泛型
这里要注意的一件重要事实是,使用Java泛型,<T extends MinimalPerson>
将匹配Person和MinimalPerson。