0

Here my case: I code a function which will check for any object in each property (for any deep level) if there is a specific annotation and if yes it'll set the property to null. But I'm facing a problem: how to check if a property is a collection, i'll need to check for each element of the collection if there is the annotation and if yes i remove the object from the collection and set the collection with the new checked collection.

My question: how to modify this collection content using reflection?

RCM SAS
  • 95
  • 7

1 Answers1

0

Ok so this post help me a lot: Get type of a generic parameter in Java with reflection

But i still had some probleme so here a piece of code to explain:

Let say a simple class with a property of collection type:

static class Bla {
    public ArrayList<String> collection = new ArrayList<String>();
}

Now see the function to retreive the String class with reflection:

public static void check(Object object) throws IllegalArgumentException, IllegalAccessException {
    Class<?> objectClass = object.getClass();
    Field[] fields = objectClass.getFields();
    for (Field field : fields) {
      Object prop = field.get(object);
      if (prop instanceof ArrayList) {
        Type genericType = field.getGenericType(); // To get the ArrayList<String> Type object
        ParameterizedType pt = (ParameterizedType) genericType; // Cast to a ParameterizedType to
                                                                // recover the type within <T> which
                                                                // is String
        Type[] atp = pt.getActualTypeArguments();// Then call the function to get the array of type
                                                 // argument (e.g.: <T>,<V,U>,...)
        // Do something with this
      }
    }
  }

And that's all!!

RCM SAS
  • 95
  • 7