mercredi 28 juin 2023

Reflection get field of Java class

I am a little confused working with the newer versions of Java and Reflections. I have a somewhat hacky code part which requires a tiny bit of changing the Java Runtime behavior.

I want to update the parent field on the ClassLoader class. This worked with Java 8 without any issues, but trying versions like Java 11+ I get the following exception:

java.lang.NoSuchFieldException: parent
    at java.base/java.lang.Class.getDeclaredField(Class.java:2707)

So my first thought was that it has been removed or renamed, but that isn't the case. I then read about their changes to prevent reflection access with the illegal reflective access. However this was removed with Java 17.

In fact, I cannot access or get any field at all. When running the following line, I get 0 as a result (using Java 20):

System.out.println(Main.class.getClassLoader().getClass().getDeclaredFields().length);

I can somewhat understand the reason for this, but it is hard to believe that they completly prevent reflective access to the runtime. Does anybody know how I can "fix" this?

PS: I know that reflection is unsafe and should be prevented, but I cannot use an alternative to get the desired behavior of my application.





Aucun commentaire:

Enregistrer un commentaire