Reuben Tanner
Reuben Tanner

Reputation: 5565

TypeNotPresentException thrown when reflecting on a method

I've got a sub class that has a method that throws an exception in an Android project.

public class Bar extends Foo {
    public void method(String someClass) throws ReflectiveOperationException {
        Class.forName(someClass);
    }
}

I've got a base class with a method that reflects on its own methods which, of course, can be called from the subclass.

public class Foo {
    public void reflectOnMethods() {
        for (Method m : this.getClass().getDeclaredMethods()) {
           //do stuff with methods
        }
    }
}

And when Bar calls its inherited reflectOnMethods, I'm presented with a stack trace like so

02-05 21:58:04.461: E/AndroidRuntime(2737): java.lang.TypeNotPresentException: Type java/lang/ReflectiveOperationException not present
02-05 21:58:04.461: E/AndroidRuntime(2737):     at java.lang.Class.getDeclaredMethods(Native Method)
02-05 21:58:04.461: E/AndroidRuntime(2737):     at java.lang.Class.getDeclaredMethods(Class.java:703)

The issue goes away when I change the thrown exception from ReflectiveOperationException to ClassNotFoundException but WHY IS THAT THE FIX??!!?

I'm puzzled by it and would look into the JDK source to try to figure it out but I'm feeling lazy.

Upvotes: 2

Views: 3258

Answers (1)

tomrozb
tomrozb

Reputation: 26251

The problem is you're trying to run the code on API <19, but the ReflectiveOperationException is base class for ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException and NoSuchMethodException since API 19.

Do not use ReflectiveOperationException in throws clause if you want compatibility with API levels below 19.

public class Bar extends Foo {
    public void method(String someClass) throws ClassNotFoundException {
        Class.forName(someClass);
    }
}

Upvotes: 1

Related Questions