4

One problem I've noticed when porting reflection code from Java 8 to Java 9+ is that setAccessible() now throws InaccessibleObjectException in addition to SecurityException when before in Java 8 InaccessibleObjectException wasn't an exception type.

What is the accepted way to write code that has to catch and handle an exception that it can't know about since it's in a future Java version yet still be compatible with the current version? (In this case the only ancestor class is RuntimeException, but that feels like a smell to me personally to write such an all-encompassing catch.)

Kitten
  • 437
  • 3
  • 13

1 Answers1

1

You could ask the runtime for the Java version (as described in this post) and use exception.getClass().getName() to get the exception class name in a backward-compatible way

In other words

  try {
    method.setAccessible();
  } catch (RuntimeException e) {
    String version = (System.getProperty("java.version"))
    String minorVersion = ver.split("\\.")[1];
    if (minorVersion >=9) {
      if (e.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) {
        // Handle java 9 reflection access issue
      } else {
        // Handle java 8 runtime exception
    }
  }





chertar
  • 11
  • 1
  • 4
  • It's a valid solution but it seems "syntactically heavy" if you get what I mean. (And by the way, welcome to Stack Overflow!) – Kitten Jan 31 '19 at 00:54
  • Thanks! Another idea I had was to use `Class.forName(...)` and catch `ClassNotFoundException` but that involves about as much code. You could of course put the handling code in a static function on a utility class but not sure if that was your concern. – chertar Jan 31 '19 at 01:17
  • 1
    Technically you'd need to go up the superclass chain. / You don't need to check version. / Handling the runtime exception would be just `throw e;`. – Tom Hawtin - tackline Jan 31 '19 at 04:25
  • No need to check for the Java version. But since `InaccessibleObjectException` is not `final` and could have sub-classes, you should check all super-classes of `e` as well. – Thilo Jan 31 '19 at 05:53