如何根据一个条件调用不同的POJO实例



我有两个POJO,即具有不同属性集的学生教师。我有一个函数来打印两个POJO的属性,即printStudent((printTeacher((

printStudent(Student s){
String res = "";
res+ = s.getA1();
res+ = s.getA2();
res+ = s.getA3();
System.out.println(res);
}
printTeacher(Teacher t){
String res = "";
res+ = t.getA1();
res+ = t.getA2();
res+ = t.getA3();
System.out.println(res);
}

现在我想实现两件事:1.循环遍历POJO的属性,这样我就不必串行执行。2.制作一个通用函数,根据ID选择要接受的POJO通过以下方式:

print(Object o,id){
if(id==0){
String res = loop through student pojo
}
else{
String res = loop through teacher pojo
}
}

有人能建议我如何实现这一点吗?或者如果可能的话?

添加像这样的通用接口怎么样

public interface Printable {
void print()
}

然后在两个类中实现它:

public class Teacher implements Printable {
private String A1;
...
public void print() {
System.out.println(getA1())
}
}
public class Student implements Printable {
private String A1;
private String A2;
...
public void print() {
String res = getA1() + " " + getA2();
System.out.println(res);
}
}

然后在基类中使用你的函数

public class App {
public void print(Printable printable) {
printable.print();
}
}

您可以使用Lombok的@ToStringanotation为类生成toString方法。然后你可以有一个通用接口,例如@AzJa建议的Printable,并在该接口中编写一个默认方法:

default void print() {
System.out.println(this.toString());
}

最新更新