vendredi 5 mars 2021

java 8 reflection: how to iterate on a private final java.util.Vector field

I would like to get a reference with Java reflection to a java.util.Vector private variable defined in a class and iterate on it. The declaration of the variable in the class is the following: private final Vector<Class<?>> classes = new Vector<>();

Actually, the class from where I am trying to read the Vector is this one: java.lang.ClassLoader

The object I need comes from this (I need to use getSuperclass() twice because in the application server ClassLoader.getSystemClassLoader() returns with a weblogic specific classloader class and the field I need comes from the parent class):

ClassLoader.getSystemClassLoader().getClass().getSuperclass().getSuperclass()

And the field in debug mode, I need:

enter image description here

A little bit about the context: the java reflection code will run in a simple servlet, deployed to an application server.

I am able to get the java.lang.reflect.Field with the following code:

Class c = ClassLoader.getSystemClassLoader().getClass().getSuperclass().getSuperclass();
Field classesField = c.getDeclaredField("classes");
classesField.setAccessible(true);
Type type = classesField.getGenericType();
System.out.println(type.getTypeName()); //java.util.Vector

Result: enter image description here

But I am not able to get a reference from java.lang.reflect.Field to java.util.Vector in order to I can read the items from it.

I have tried this ways:

// 1:
Vector v = new Vector<>();
// ERROR: Can not set final java.util.Vector field java.lang.ClassLoader.classes to java.util.Vector

// 2:
public static class VectorWrapper {
    private Vector<Class<?>> v = new Vector<>();
}
VectorWrapper v = new VectorWrapper();
// ERROR: Can not set final java.util.Vector field java.lang.ClassLoader.classes to a.b.c.Test$VectorWrapper

// try to get the vector
Object o = classesField.get(v);
Vector classes = (Vector<Class<?>>) o;
System.out.println(classes.size());

The codes above do not work, throws exception.

It seems that because the field in the class is defined final I am not able go get the reference. Maybe I need to get the Iterator of the Vector instead of the Vector itself? But I am not sure about it.

How can I loop on this Vector field and geat the items from it?





Aucun commentaire:

Enregistrer un commentaire