Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Many methods in the org.springframework.util.ReflectionUtils package have been deprecated, but there is no hint which methods should be used as a replacement. How are the following methods to be replaced properly?

org.springframework.util.ReflectionUtils.makeAccessible();
org.springframework.util.ReflectionUtils.isAccessible();

My goal is to get all field names and save them into a Map. So far the following code worked, but how can I replace the deprecated methods?

ReflectionUtils.doWithFields(object.getClass(), field -> {
            if (!field.isAccessible()) ReflectionUtils.makeAccessible(field);
            map.put(field.getName(), ReflectionUtils.getField(field, object));
                It is deprecated because it is deprecated in the JVM (and probably will be removed and disallowed). This will probably already get you into issues with a JPMS based (Module-Path instead of ClassPath) based system as you are severely restricted in what you can see and do with reflection. (Which is also why it is deprecated and going to be removed from the JDK).
– M. Deinum
                Aug 14, 2018 at 9:05

Because of module system accessible checks and changes uses now new methods, to make something accessible you should look at trySetAccessible:
https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/AccessibleObject.html#trySetAccessible()
it returns true/false value instead of exception.

And to check for access use canAccess(object):

object - an instance object of the declaring class of this reflected object if it is an instance method or field

https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/AccessibleObject.html#canAccess(java.lang.Object)

So I would leave out the check if the field is accessible at all, and just execute trySetAccessible() instead of makeAccessible? – membersound Aug 14, 2018 at 20:11 yep, it should work fine too. (unless that class is from other module that does not want to allow reflective access on it) – GotoFinal Aug 15, 2018 at 10:27

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.