2

I have this code:

FVDTO.setStatus("fail"); List<String[]> invalidFields = new ArrayList<String[]>(); Iterator<ConstraintViolation<HazardSubmission>> iterator = cv.iterator(); while(iterator.hasNext()) { ConstraintViolation<HazardSubmission> i = iterator.next(); String property = i.getPropertyPath().toString(); String message = i.getMessage(); invalidFields.add(new String[] { property, message }); } FVDTO.setInvalidFields(invalidFields); return new JsonResolution(FVDTO); 

I've taken some out to keep things DRY so I can then use it with other classes, i.e HazardSubmission is one class, and there will be others. The below code shows my attempt, obviously manually casting <HazardSubmission> here won't work it needs to be like o.getClass();

public static List<String[]> GetInvalidProperties(Set<ConstraintViolation<Object>> cv, Object o) { List<String[]> invalidFields = new ArrayList<String[]>(); Iterator<ConstraintViolation<HazardSubmission>> iterator = cv.iterator(); while(iterator.hasNext()) { ConstraintViolation<HazardSubmission> i = iterator.next(); String property = i.getPropertyPath().toString(); String message = i.getMessage(); invalidFields.add(new String[] { property, message }); } 

}

The second code block fails because I don't really know what I'm doing, I want to pass in the cv for param 1, with a general object type, then somehow pass in the type as a second paramter.

Could you someone please explain how to do this?

2
  • 1
    I haven't used hibernate, but the whole point of using generics so you don't have to cast Commented Mar 23, 2012 at 2:26
  • Why do you want Object in the parameter when your method is only working on HazardSubmission? Commented Mar 23, 2012 at 2:33

2 Answers 2

1

I think you might be looking for a generic method

public static <T> List<String[]> GetInvalidProperties(Set<ConstraintViolation<T>> cv){ Iterator<ConstraintViolation<T>> iterator = cv.iterator(); while(iterator.hasNext()) { ConstraintViolation<T> i = iterator.next(); String property = i.getPropertyPath().toString(); String message = i.getMessage(); invalidFields.add(new String[] { property, message }); } } 

If all T extends a given class or interface you could even say

public static <T extends MyClassOrInterface> List<String[]> GetInvalidProperties(Set<ConstraintViolation<T>> cv){ //... } 
Sign up to request clarification or add additional context in comments.

Comments

0

cv.iterator() will return you an Iterator<ConstraintViolation<Object>>, and you need Iterator<ConstraintViolation<HazardSubmission>>. This is done because cv is defined as Set<ConstraintViolation<Object>>. If you want a generic way for this, you can change

Set<ConstraintViolation<Object>> cv 

to

Set<ConstraintViolation<? extends Object>> cv 

in that way your code will compile.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.