lundi 22 juin 2020

Collection Contents of Private Java Fields

Let's assume I have a class that looks something like:

public class HasCollection() {
  private List<Class> exceptions;
}

In this example, exceptions is a private collection of any kind of exception (Runtime, IllegalArgument, NullPointer, take your pick).

If I want to access that via reflections, I would use this (assume instance is a HasCollection):

Field exceptions = HasCollection.class.getDeclaredField("exceptions");
exceptions.setAccessible(true);
List<Class> privateExceptions = new ArrayList<>((List<Class>) exceptions.get(instance));

But this only almost works. Instead of the actual classes that are in the list, instead I get a bunch of com.my.class.hierarchy.InstanceOf instances. Those don't de/serialize properly (using Jackson). Is there anything I can do about that without knowing a priori what classes those instances actually represent?





Aucun commentaire:

Enregistrer un commentaire