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

问题描述 投票:0回答:1

我有两个POJO,分别是StudentTeacher,它们具有不同的属性集。我有一个函数可以打印两个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
      }
    }

任何人都可以建议我如何实现这一目标,或者完全有可能吗?

java spring-boot spring-mvc
1个回答
0
投票

如何添加通用接口,如:

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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.