Example usage for java.lang.reflect Constructor isAccessible

List of usage examples for java.lang.reflect Constructor isAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Constructor isAccessible.

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:org.sonar.java.checks.CheckListTest.java

@Test
public void private_constructor() throws Exception {
    Constructor constructor = CheckList.class.getDeclaredConstructor();
    assertThat(constructor.isAccessible()).isFalse();
    constructor.setAccessible(true);//from   w  w  w  . j av a2 s .co  m
    constructor.newInstance();
}

From source file:org.sonar.java.se.NullableAnnotationUtilsTest.java

@Test
public void private_constructor() throws Exception {
    assertThat(Modifier.isFinal(NullableAnnotationUtils.class.getModifiers())).isTrue();
    Constructor<NullableAnnotationUtils> constructor = NullableAnnotationUtils.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    assertThat(constructor.isAccessible()).isFalse();
    constructor.setAccessible(true);/*from ww w  . j av a2  s  .c o m*/
    constructor.newInstance();
}

From source file:org.codehaus.griffon.commons.AbstractGriffonClass.java

public Object newInstance() {
    try {//from w ww . j a  va 2 s .  c om
        Constructor<?> defaultConstructor = getClazz().getDeclaredConstructor(new Class[] {});
        if (!defaultConstructor.isAccessible()) {
            defaultConstructor.setAccessible(true);
        }
        return defaultConstructor.newInstance(new Object[] {});
    } catch (Exception e) {
        Throwable targetException = null;
        if (e instanceof InvocationTargetException) {
            targetException = ((InvocationTargetException) e).getTargetException();
        } else {
            targetException = e;
        }
        throw new NewInstanceCreationException(
                "Could not create a new instance of class [" + getClazz().getName() + "]!", targetException);
    }
}

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

private <T> T loadInstance(Class<T> clazz, Map<String, String> properties) {
    try {/*from  w  ww.  j a v a  2  s  .  c o m*/
        // Create new object of class using default constructor:
        Constructor<T> constructor = clazz.getDeclaredConstructor();
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        T instance = constructor.newInstance();

        // Iterate over all existing properties and fill fields of new object:
        for (Map.Entry<String, String> entrySet : properties.entrySet()) {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.getName().equals(entrySet.getKey())) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    field.set(instance, stringToObject(field.getType(), entrySet.getValue()));
                    break;
                }
            }
        }
        return instance;
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("Cannot find default constructor of class " + clazz, ex);
    } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new IllegalStateException("Error during value assignment.", ex);
    }
}

From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java

/**
 * Support method.//ww w.j  a v a 2s .c  om
 *
 * @param clz
 * @return
 */
private Object invokeInnerClassConstructor(Class<?> clz) {
    try {
        Constructor<?> noArgConstructor = clz.getDeclaredConstructor(SimpleAmqpMessageContainer.class);
        if (!noArgConstructor.isAccessible()) {
            noArgConstructor.setAccessible(true);
        }

        return noArgConstructor.newInstance(this);
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
            | InvocationTargetException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:io.dataplay.storm.workers.AbstractBoltTest.java

/**
 * Ensure the constructor is abstract./*w  w w. j  a  va2 s.  c  o m*/
 *
 * @throws Exception Creating an abstract class should throw an error.
 */
@Test
public void testConstructor() throws Exception {
    Constructor<AbstractBolt> constructor = AbstractBolt.class.getDeclaredConstructor();

    // Must not be accessible (abstract)
    Assert.assertFalse(constructor.isAccessible());

    // Assert interface
    Class[] interfaces = AbstractBolt.class.getInterfaces();
    Assert.assertTrue(ArrayUtils.contains(interfaces, IDataWorker.class));

    // Override the private constructor and create an instance
    try {
        constructor.newInstance();
        Assert.fail("Constructor must not be accessible");
    } catch (InstantiationException e) {
        Assert.assertTrue(true);
    }

    // Assert extensibility.
    IDataWorker worker = new WorkerImpl();
    Assert.assertNotNull(worker);

}

From source file:com.transitionseverywhere.TransitionInflater.java

private Object createCustom(AttributeSet attrs, Class expectedType, String tag) {
    String className = attrs.getAttributeValue(null, "class");

    if (className == null) {
        throw new InflateException(tag + " tag must have a 'class' attribute");
    }//from  www . ja v  a  2  s.  c  om

    try {
        synchronized (sConstructors) {
            Constructor constructor = sConstructors.get(className);
            if (constructor == null) {
                Class c = mContext.getClassLoader().loadClass(className).asSubclass(expectedType);
                if (c != null) {
                    constructor = c.getConstructor(sConstructorSignature);
                    if (!constructor.isAccessible()) {
                        constructor.setAccessible(true);
                    }
                    sConstructors.put(className, constructor);
                }
            }

            return constructor.newInstance(mContext, attrs);
        }
    } catch (InstantiationException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (ClassNotFoundException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (InvocationTargetException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (NoSuchMethodException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (IllegalAccessException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    }
}

From source file:com.payu.sdk.util.UtilTest.java

/**
 * Private constructor test/*  w w  w  . j av  a2  s  .c o  m*/
 *
 * @param clasz
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
@SuppressWarnings("rawtypes")
private void privateConstructorTest(Class clasz) throws IllegalArgumentException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    Constructor[] ctors = clasz.getDeclaredConstructors();
    Assert.assertEquals(1, ctors.length, "Utility class should only have one constructor");
    Constructor ctor = ctors[0];
    Assert.assertFalse(ctor.isAccessible(), "Utility class constructor should be inaccessible");
    ctor.setAccessible(true); // obviously we'd never do this in production
    Assert.assertEquals(clasz, ctor.newInstance().getClass(),
            "You'd expect the construct to return the expected type");
}

From source file:org.j2free.servlet.EntityAdminServlet.java

/**
 *
 * @param request//from  w  w  w .  j a  va 2  s  .  co m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Controller controller = Controller.get(); // Get the controller associated with the current thread;

    String uri = request.getRequestURI();
    uri = uri.replaceFirst(".*?/(list|find|inspect|create|save|update|delete)", "$1"); // chop off the part before what we care about
    String path[] = uri.split("/");

    log.debug(uri);
    log.debug("path.length = " + path.length);

    if (path.length < 1) {
        log.debug("too little path info " + uri);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    RequestDispatcher rd = null;

    if (path[0].equals("list")) {
        log.debug("in list");
        if (path.length < 2) {
            log.debug("too few parts for list");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            int start = ServletUtils.getIntParameter(request, "start", 0);
            int limit = ServletUtils.getIntParameter(request, "limit", 100);

            List entities;
            if (path.length == 3) {
                String[] stringIds = path[2].split(",");
                Object[] ignoredIds = new Object[stringIds.length];

                Class idType = marshaller.getIdType();

                // NOTE: this will only work with integer entityIds
                if (idType == Integer.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = Integer.parseInt(stringIds[i]);
                } else if (idType == String.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = stringIds[i];
                } else if (idType == Long.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = Long.parseLong(stringIds[i]);
                }

                entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()),
                        Restrictions.not(Restrictions.in(marshaller.getIdName(), ignoredIds)));
            } else
                entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()));

            TreeMap<String, Object> entityMap = new TreeMap<String, Object>();
            for (Object obj : entities) {
                entityMap.put(marshaller.extractId(obj).toString(), obj);
            }

            request.setAttribute("start", start);
            request.setAttribute("limit", limit);

            request.setAttribute("total", controller.count(klass));

            request.setAttribute("simpleName", klass.getSimpleName());
            request.setAttribute("package", klass.getPackage().getName() + ".");
            request.setAttribute("entities", entityMap);

            if (ServletUtils.getBooleanParameter(request, "selector", false))
                rd = request.getRequestDispatcher(Dispatch.ENTITY_SELECTOR);
            else
                rd = request.getRequestDispatcher(Dispatch.ENTITY_LIST);

        } catch (Exception e) {
            log.error("Error listing entities", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("find") || path[0].equals("inspect")) {
        log.debug("in find");
        if (path.length < 3) {
            log.debug("too few parts for find");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));
            request.setAttribute("entity", entity);
            request.setAttribute("entityId", marshaller.extractId(entity));
            request.setAttribute("fields", marshaller.marshallOut(entity, true));

            if (path[0].equals("find"))
                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            else
                rd = request.getRequestDispatcher(Dispatch.ENTITY_INSPECT);

        } catch (Exception e) {
            log.error("error finding entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("create")) {
        log.debug("in create");
        if (path.length < 2) {
            log.debug("too few parts for create");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Constructor zeroArgsConst = klass.getConstructor();
            if (!zeroArgsConst.isAccessible())
                zeroArgsConst.setAccessible(true);

            Object entity = zeroArgsConst.newInstance();
            request.setAttribute("simpleName", klass.getSimpleName());
            request.setAttribute("package", klass.getPackage().getName() + ".");
            request.setAttribute("fields", marshaller.marshallOut(entity, true));

            rd = request.getRequestDispatcher(Dispatch.ENTITY_CREATE);

        } catch (Exception e) {
            log.error("error creating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("save")) {
        log.debug("in save");

        if (path.length < 2) {
            log.debug("too few parts for save");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        Marshaller marshaller = null;

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = klass.newInstance();

            entity = marshaller.marshallIn(entity, request.getParameterMap(), controller);

            controller.persist(entity, true);

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);

                // need this to display dates in the DB stored format
                entity = controller.findPrimaryKey(klass, marshaller.extractId(entity));

                request.setAttribute("entity", entity);
                request.setAttribute("entityId", marshaller.extractId(entity));
                request.setAttribute("fields", marshaller.marshallOut(entity, true));

                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            }

        } catch (MarshallingException e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else if (path[0].equals("update")) {
        log.debug("in update");

        if (path.length < 3) {
            log.debug("too few parts for update");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));

            entity = marshaller.marshallIn(entity, request.getParameterMap(), controller);

            controller.merge(entity);

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);

                // need this to display dates in the DB stored format
                entity = controller.findPrimaryKey(klass, marshaller.extractId(entity));

                request.setAttribute("entity", entity);
                request.setAttribute("entityId", marshaller.extractId(entity));
                request.setAttribute("fields", marshaller.marshallOut(entity, true));

                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            }

        } catch (MarshallingException e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            log.error("error updating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else if (path[0].equals("delete")) {

        log.debug("in delete");

        if (path.length < 3) {
            log.debug("too few parts for delete");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));

            controller.remove(entity);
            entity = null;
            controller.flush();

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);
                return;
            }

        } catch (Exception e) {
            log.error("error updating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else {
        log.debug("Don't know what to do!");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    CharArrayWrapper responseWrapper = new CharArrayWrapper((HttpServletResponse) response);
    rd.forward(request, responseWrapper);

    String responseString = responseWrapper.toString().replaceAll("\n", " ").replaceAll("\\s{2,}", " ")
            .replaceAll("> ", ">").replaceAll(" <", "<").replaceAll(" />", "/>");
    response.setContentLength(responseString.length());
    response.setContentType("text/javascript");

    PrintWriter out = response.getWriter();
    out.write(responseString);
    out.flush();
    out.close();
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * New instance.//from   w  w w  .  ja v a 2  s .  co m
 * 
 * @param <T>
 *          the generic type
 * @param clazz
 *          the clazz
 * @param paramTypes
 *          the param types
 * @param arguments
 *          the arguments
 * @return the t
 */
public static <T> T newInstance(Class<T> clazz, Class<?>[] paramTypes, Object[] arguments) {
    T instance = null;

    try {
        // Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        Constructor<T> constructor = clazz.getDeclaredConstructor(paramTypes);
        boolean access = constructor.isAccessible();
        constructor.setAccessible(true);
        instance = constructor.newInstance(arguments);
        if (!access) {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        logger.error(e);
    }
    return instance;
}