lundi 29 mai 2017

Java generics - Type casting issue

I have a generic method which accepts class type and fields of that class to be updated. For ex:

class A {
  private int a;
  private int b;
}

class B {
 private int c;
 private int d;
}

At run time, if we pass class type as "A.class" and fieldstoBeUpdated as "b", what is the best way to access the field's getter/setter of that particular class, so that we can modify the fields.

public <T> void find(T clazz, List<String> fieldsToBeUpdated) {
            if (clazz instanceof A) {
                fieldsToBeUpdated.parallelStream().forEach(field -> {
                    switch(field) {
                    case "a":((A)p).setCreatedTime(TimeUtils.toGMT(((A)p).getCreatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    case "b":((A)p).setUpdatedTime(TimeUtils.toGMT(((A)p).getUpdatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    }
                });
            }

            if (clazz instanceof B) {
                fieldsToBeUpdated.parallelStream().forEach(field -> {
                    switch(field) {
                    case "c":((B)p).setCreatedTime(TimeUtils.toGMT(((B)p).getCreatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    case "d":((B)p).setUpdatedTime(TimeUtils.toGMT(((B)p).getUpdatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    }
                });
            }
}

I have written above code to achieve the same.

But the problem is that i have 30 such classes to be passed as a parameter to this generic method with list of fields of that class to update/modify.

Its not the correct implementation to write 30 such if statements checking for the class type and then type casting the object to that class.

Is there any better way to achieve the same ?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire