Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.report.validator;
- import com.report.excel.Employee;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.List;
- public class Validator {
- public List<Error> validate(Object object) {
- Error error = null;
- List<Error> errors = new ArrayList<>();
- Class<?> thisClass = null;
- try {
- thisClass = Class.forName(object.getClass().getName());
- Field[] aClassFields = thisClass.getDeclaredFields();
- for (Field f : aClassFields) {
- Field field = object.getClass().getDeclaredField(f.getName());
- field.setAccessible(true);
- Object value = field.get(object);
- System.out.println(value);
- if (value instanceof String) {
- error = validateString(value.toString(), f.getName());
- if (error != null) {
- errors.add(error);
- }
- } else if (value instanceof Integer) {
- error = validateInt((Integer) value, f.getName());
- if (error != null) {
- errors.add(error);
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return errors;
- }
- private Error validateString(String field, String fieldName) {
- Error error = null;
- if (field.isEmpty()) {
- error = new Error(fieldName, fieldName + " Shouldn't be empty");
- }
- if (field == null) {
- error = new Error(fieldName, fieldName + " Shouldn't be null");
- }
- return error;
- }
- private Error validateInt(Integer field, String fieldName) {
- Error error = null;
- if (field.intValue() == 0) {
- error = new Error(fieldName, fieldName + " Shouldn't be 0");
- }
- if (field == null) {
- error = new Error(fieldName, fieldName + " Shouldn't be null");
- }
- return error;
- }
- public static void main(String[] args) {
- Validator validator = new Validator();
- Employee employee = new Employee(0, "", "s@gmail.com", "IT");
- System.out.println(validator.validate(employee));
- }
- }
- package com.report.validator;
- public class Error {
- private String fieldName;
- private String errorMessage;
- public String getFieldName() {
- return fieldName;
- }
- public void setFieldName(String fieldName) {
- this.fieldName = fieldName;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public Error() {
- }
- public Error(String fieldName, String errorMessage) {
- this.fieldName = fieldName;
- this.errorMessage = errorMessage;
- }
- @Override
- public String toString() {
- return "Error{" +
- "fieldName='" + fieldName + '\'' +
- ", errorMessage='" + errorMessage + '\'' +
- '}';
- }
- }
Add Comment
Please, Sign In to add comment