简体   繁体   中英

ReflectionUtils how to replace deprecated methods?

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));
        });

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM