我有一個場景來獲取子字段的子層次結構,直到父級進行字段級驗證。 有人可以提供一些解決方案。獲取子級層次結構路徑,直到java中的父項爲止
POJO類
Student.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.List;
public class Student {
private String studentName;
private List<Subject> subjects;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public List<Subject> getSubjects() {
if (subjects == null) {
return new ArrayList<>();
}
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
}
Subject.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.List;
public class Subject {
private String subjectName;
private List<RevisionMarks> revisionMarks;
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public List<RevisionMarks> getRevisionMarks() {
if (revisionMarks == null) {
return new ArrayList<>();
}
return revisionMarks;
}
public void setRevisionMarks(List<RevisionMarks> revisionMarks) {
this.revisionMarks = revisionMarks;
}
}
RevisionMarks.java
package com.poc.next.validations;
public class RevisionMarks {
private Integer mark;
private String revision;
public Integer getMark() {
return mark;
}
public void setMark(Integer mark) {
this.mark = mark;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
}
現在我們添加一個驗證來檢查在RevisionMarks類中的給定標記是否有效。如果它等於零,我必須將其添加到錯誤dto並將其發送回UI。這裏面臨的挑戰是我必須提供像「主體[0] .revisionMarks [0] .mark」一樣的動態層次結構。
主類 RevisionValidation.java
package com.poc.next.validations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RevisionValidation {
public static void main(String[] args) {
Student student = populateStudentData();
Iterator<Subject> iterator = student.getSubjects().iterator();
while (iterator.hasNext()) {
Subject subject = (Subject) iterator.next();
RevisionMarks revisionMarks = subject.getRevisionMarks().get(0);
System.out.println(revisionMarks.getMark());
if (revisionMarks.getMark() == 0) {
ErrorDTO errorDTO = new ErrorDTO(true, "Invalid Marks", "Error", "subjects[0].revisionMarks[0].mark",
"invalid_mark");
System.out.println(errorDTO);
}
}
}
private static Student populateStudentData() {
List<RevisionMarks> revisionMarks = new ArrayList<>();
RevisionMarks revisionMark = new RevisionMarks();
revisionMark.setMark(0);
revisionMark.setRevision("Test 1");
revisionMarks.add(revisionMark);
List<Subject> subjects = new ArrayList<>();
Subject subject = new Subject();
subject.setSubjectName("CS");
subject.setRevisionMarks(revisionMarks);
subjects.add(subject);
Student student = new Student();
student.setStudentName("Sample");
student.setSubjects(subjects);
return student;
}
}
如何動態創建一個像 「科目[0] .revisionMarks [0] .mark」 fieldPath會。 歡迎任何建議。提前致謝。
添加一個計數器,您在循環的每次迭代中增加 –
謝謝..這有助於.. – Shiva