The inner class needed to be static

I was getting a java.lang.InstantiationException when I tried to call clazz.newInstance() to reflectively instantiate some classes.

Here are the steps I tried as I worked to understand what was happening:

  1. The newInstance() call was being performed in a method in the production code.  I thought maybe there was something odd about how I was passing a Class<? extends TransactionManagerLookup> object into that method under test, so I tried performing the reflective instantiation call locally, in my test method:
        PlainLookup.class.newInstance();

    Same error as before.

  2. Next, I tried instantiating my class directly, with
        new PlainLookup();

    That worked.  Ok…

  3. The thing I was trying to reflectively instantiate was of type Class<? extends TransactionManagerLookup>.  I thought maybe the TransactionManagerLookup interface was somehow gumming up the reflective instantiation, so I created an empty class called PlainClass, which did not implement TransactionManagerLookup, and tried
    PlainClass.class.newInstance();

    Same error, while again, new PlainClass() worked fine.

  4. My next question was, can I use newInstance() to successfully instantiate anything? I tried
    Object.class.newInstance();

    and did not get the error.

  5. At this point I was confused and asked Ben if he would take a look at it. In the process of explaining my woes, one of us — I don’t remember if it was Ben or me — noticed that PlainClass and PlainLookup, which are inner classes of my test class, were not static inner classes.

Adding static to the class definitions fixed the issue!  There’s theory behind that, but for now I’ll just quote Joshua Bloch on the matter: “Favor static member classes over nonstatic” (Item 22 in Effective Java (2nd ed.)).  I had forgotten…

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s