Dashboard > People > Uwe Schaefer > Browse Space > News Items for
  codesmell Log In   View a printable version of the current page.  
  News Items for Jun 16, 2008
  2008/06/16

Did you ever try to create an instance of a class with a protected constructor from outside its package?
I ran into this need when working with JPA-Entities of which i wanted to know initial field values. (yeah, i know. kind of black magic...)

It is actually easier, than getting protected Fields:

public static <T> T newInstance(final Class<T> c)
    {
        try
        {
            Constructor<T> constructor = c.getDeclaredConstructor(new Class[] {});
            if (constructor != null)
            {
                constructor.setAccessible(true);
                return constructor.newInstance((Object[]) null);
            }
            else
            {
                throw new IllegalArgumentException("Cannot find empty Contructor for class '" + c.getName() + "'");
            }
        }
        catch (SecurityException e)
        {
            throw ExceptionHelper.wrap(e);
        }
        catch (IllegalArgumentException e)
        {
            throw ExceptionHelper.wrap(e);
        }
        catch (InstantiationException e)
        {
            throw ExceptionHelper.wrap(e);
        }
        catch (IllegalAccessException e)
        {
            throw ExceptionHelper.wrap(e);
        }
        catch (InvocationTargetException e)
        {
            throw ExceptionHelper.wrap(e);
        }
        catch (NoSuchMethodException e)
        {
            throw ExceptionHelper.wrap(e);
        }
    }
Posted at 16 Jun @ 7:47 PM by Uwe Schaefer | 0 comments

Juni 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

Nov 06, 2008
Jun 15, 2008

This site is powered by a free Atlassian Confluence Personal Server License. Evaluate Confluence for your organisation or read more about Confluence licensing here.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.2.9 Build:#527 Sep 07, 2006) - Bug/feature request - Contact Administrators