Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Any issue in setting the accessiblilty of java.lang.reflect Field to true?

I’m trying to write a generic function to print the individual fields of any object. I’m using java.lang.reflect.Field to get the individual fields in the onject. However the code only works if I set the accessible property of that field to true, as highlighted in the code below. My only concern is, would this lead to any issue anywhere else where I’m using the object?

Field[] fields = MyClass.class.getDeclaredFields();
for(Field field : fields) {
    try {
        field.setAccessible(true); // Would this lead to any issue anywhere else?
        Object obj = field.get(m); // m is a sample object of MyClass
        System.out.println("Object: " + obj);
    } catch (Exception e) {
        System.out.println("Illegal Access Exception : " + e);
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, that means your code will not work on any modularized (as in, module-info.java, that specific kind of modularized) system running on JVM21 and up.

If module A does not expose some element to module B (usually because it doesn’t export that at all, possibly because A only exports it to an explicitly enumerated list of modules), then .setAccessible doesn’t work, and nothing will short of --add-opens switches when starting java.

More generally ‘print all fields of an object’ is breaking encapsulation rules that you shouldn’t be breaking – java is not that kind of language. If you want to ‘print an object’, then the class definition (the .java source file containing the public class Foo definition representing that class) needs to have a method that does that. If it does not have that method you will have to edit that source file to add it, and if you can’t do that, then you will have to live with it.

If the purpose is specifically debugging, you might be better off using the debugger infrastructure (JVMTI – you can search the web for that, or load as an agent, ‘java agent’ is also searchable for tutorials). You’d need completely different code for that, you don’t, generally, use reflection in agents.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading