williamsandonz
williamsandonz

Reputation: 16420

How can I cast Generics in Java?

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?

Upvotes: 2

Views: 299

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

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){
     //...
}

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 0

Related Questions