top of page

Easier Exception Handling for Reflective Methods- Java 7 feature

Java 7 version came up with many new features.

One of the feature was introduced in exception handling mechanism for reflective methods which is rarely used since Reflection API (under java.lang.reflect package). It is generally used in IDEs, code analyzers, test tools and some other tools.

We know that with reflection feature, we can examine or modify the behavior of methods, classes, interfaces at runtime, irrespective of the access specifier used with them (including private variables).

Till Java 6, when we have to call a reflective method, we need to catch multiple unrelated checked exceptions. Java 7 added a new super class Exception 'ReflectiveOperationException' for reflective operations.

For example,If we don't know the name at compile time, but have the class name as a string at runtime, we can do like this:

String className = Class.forName(className);

Now, Let's say we create a class and invoke its main method:

Class.forName(className).getMethod("main").invoke(null, new String[] {});

This line of code can cause multiple exceptions:

a) ClassNotFoundException,

b) NoSuchMethodException, c) IllegalAccessException, or InvocationTargetException.

In Java we can combine all the exceptions and use the multi-catch feature of Java 7:

catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { ... }

But Java 7 introduced this new super class exception and it provides a common superclass for related exceptions. We can catch all of these exceptions in a single handler: catch (ReflectiveOperationException ex) { ex.printStackTrace(); }

Happy Learning!

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ReflectiveOperationException.html

 

TARUN CHHABRA

Contact

Follow

  • LinkedIn
  • Facebook
  • Instagram

+91-9818725584

©2017 BY TARUNCHHABRA.COM. PROUDLY CREATED WITH WIX.COM

bottom of page