protected Constructors

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:

 Java |  copy |? 
public static <t> T newInstance(final Class</t><t> c)
    {
        try
        {
            Constructor</t><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);
        }
    }
                </t>

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>