Class.newInstance(): Deflecting Reflection Errors
Tuesday February 19, 2008
There’s a key bit of information I missed when glossing over the Java API that cost me an obscene amount of time.
That said I was careless enough to forget this crucial piece of information, which I’m sure was brought up in my Advanced Programming class at some point.
So if you’re running into the issue (a well-deserved IllegalAccessException):
Can not call newInstance() on the Class for java.lang.Class
Then you’ll more than likely have an excess getClass() call somewhere, e.g.:
Class<?> type = SomeImplementingClass.class;
SomeInterface _obj = (SomeInterface) type.getClass().newInstance();
If you call getClass() too many times, you’ll end up returning the class java.lang.Class, which cannot be instantiated. Factor out the getClass():
SomeInterface _obj = (SomeInterface) type.newInstance();
Schoolboy error, but I found the need to further the headache by assuming Reflection was complicated :(