0

i'm having problem with correcting bugs on this project on sonarcloud that has a IsAccessible, a deprecated function on Java 9+. I get a compilation error when i do mvn test even after replacing the code with the latest function.

I replaced this code:

static <T> T getFieldValue(Object object, Field field) {
    boolean accessible = field.isAccessible();
    Object value = null;
    try {
        if (!accessible) {
            field.setAccessible(true);
        }
        value = field.get(object);
    } catch (IllegalAccessException ignored) {
    } finally {
        field.setAccessible(accessible);
    }
    return (T) value;
}

With this code, according to the documentation:

static <T> T getFieldValue(Object object, Field field) {
    boolean accessible = field.canAccess(object);
    Object value = null;
    try {
        if (!accessible) {
            field.setAccessible(true);
        }
        value = field.get(object);
    } catch (IllegalAccessException ignored) {
    } finally {
        field.setAccessible(accessible);
    }
    return (T) value;
}

But when i do the maven test i see this error: mvn test

I don't know what else to do. Thank you in advance

  • What Java version is your Maven running with? And what source/target versions did you set? – Thomas Dec 21 '22 at 11:29
  • Maven is running Java Version 11.0.16.1. 1.8 1.8 – letterspacing Dec 21 '22 at 12:10
  • Well, that's the problem then: when Java 8 is your source and target version `canAccess()` won't be available as this method got added in Java 9. – Thomas Dec 21 '22 at 12:32
  • So which version and target should i use according to you? Thank you – letterspacing Dec 21 '22 at 12:33
  • Well, I can't tell you what version you _should_ use as there are a couple of considerations. What I can say: if you opt for Java 8 to support the widest range of environments then you can't use `canAccess()` (`isAccessible()` should still work in higher versions for now). If you want to go for a higher version (9+) I'd suggest using a LTS version, i.e. 11 or 17 - and since your environment is using 11 it would make sense to use that as the source and target version. – Thomas Dec 21 '22 at 12:37

0 Answers0