Example usage for java.lang.reflect Constructor setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:ml.shifu.shifu.util.ClassUtils.java

public static <T> T newInstance(Class<T> clazz) {
    T result;//from  w  w  w.j  a va  2 s . com
    try {
        @SuppressWarnings("unchecked")
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(clazz);
        if (meth == null) {
            meth = clazz.getDeclaredConstructor(EMPTY_CLASS_ARRAY);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(clazz, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:libepg.epg.section.body.eventinformationtable.EventInformationTableBodyTest.java

private static final EventInformationTableRepeatingPart init(byte[] data) throws InvocationTargetException {
    try {/*from   ww w . j a  va2s  .  c  om*/
        Object[] args = { data };
        Class<?>[] params = { byte[].class };
        Constructor<EventInformationTableRepeatingPart> constructor = EventInformationTableRepeatingPart.class
                .getDeclaredConstructor(params);
        constructor.setAccessible(true);
        EventInformationTableRepeatingPart target = constructor.newInstance(args);
        return target;
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException
            | SecurityException ex) {
        LOG.fatal(ex);
    }
    return null;
}

From source file:com.dianping.squirrel.client.util.ClassUtils.java

/**
 * construct instance violently// ww w.  ja  v a  2 s. c  o m
 * 
 * @param <T>
 * @param clazz
 * @param parameters
 * @return
 */
public static <T> T newInstance(Class<T> clazz, Object... parameters) {
    try {
        if (parameters == null) {
            parameters = new Object[0];
        }
        int paramLen = parameters.length;
        Class<?>[] parameterTypes = new Class<?>[paramLen];
        for (int i = 0; i < paramLen; i++) {
            parameterTypes[i] = parameters[i].getClass();
        }
        Constructor<T> constructor = getMatchingDeclaredConstructor(clazz, parameterTypes);
        boolean accessible = constructor.isAccessible();
        if (accessible) {
            return constructor.newInstance(parameters);
        } else {
            synchronized (constructor) {
                try {
                    constructor.setAccessible(true);
                    return constructor.newInstance(parameters);
                } finally {
                    constructor.setAccessible(accessible);
                }
            }
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    throw new IllegalStateException("Should never get here");
}

From source file:org.seedstack.seed.core.api.SeedException.java

/**
 * Create a new subclass of SeedException from an {@link ErrorCode}.
 *
 * @param exceptionType the subclass of SeedException to create.
 * @param errorCode     the error code to set.
 * @param <E>           the subtype.
 * @return the created SeedException./*ww  w.j  a v a2  s.c om*/
 */
public static <E extends SeedException> E createNew(Class<E> exceptionType, ErrorCode errorCode) {
    try {
        Constructor<E> constructor = exceptionType.getDeclaredConstructor(ErrorCode.class);
        constructor.setAccessible(true);
        return constructor.newInstance(errorCode);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                exceptionType.getCanonicalName() + " must implement a constructor with ErrorCode as parameter",
                e);
    }
}

From source file:org.gradle.internal.reflect.JavaReflectionUtil.java

/**
 * This is intended to be a equivalent of deprecated {@link Class#newInstance()}.
 *//*from  w  ww .j  a v  a 2 s  .c o m*/
public static <T> T newInstance(Class<T> c) {
    try {
        Constructor<T> constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();
    } catch (Throwable e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.opoo.util.ClassUtils.java

public static Constructor getDefaultConstructor(Class clazz) throws SecurityException, NoSuchMethodException {
    if (isAbstractClass(clazz))
        return null;
    Constructor constructor = clazz.getDeclaredConstructor(NO_CLASSES);
    if (!isPublic(clazz, constructor)) {
        constructor.setAccessible(true);
    }/* w w w  .  ja  v  a  2s  .c  o  m*/
    return constructor;
}

From source file:org.seedstack.seed.core.api.SeedException.java

/**
 * Wrap a subclass of SeedException with an {@link ErrorCode} around an existing {@link Throwable}.
 *
 * @param exceptionType the subclass of SeedException to create.
 * @param throwable     the existing throwable to wrap.
 * @param errorCode     the error code to set.
 * @param <E>           the subtype.
 * @return the created SeedException./*from  w w w. j  av a 2s  .  co  m*/
 */
public static <E extends SeedException> E wrap(Class<E> exceptionType, Throwable throwable,
        ErrorCode errorCode) {
    try {
        Constructor<E> constructor = exceptionType.getDeclaredConstructor(ErrorCode.class, Throwable.class);
        constructor.setAccessible(true);
        return constructor.newInstance(errorCode, throwable);
    } catch (Exception e) {
        throw new IllegalArgumentException(exceptionType.getCanonicalName()
                + " must implement a constructor with an ErrorCode and a Throwable as parameters", e);
    }
}

From source file:im.ene.lab.design.widget.swipecards.TinderView.java

private static Style parseStyle(Context context, AttributeSet attrs, String name) {
    if (TextUtils.isEmpty(name)) {
        return null;
    } else {//from w  w  w.j a  va2  s. c  o  m
        String fullName;
        if (name.startsWith(".")) {
            fullName = context.getPackageName() + name;
        } else if (name.indexOf(46) >= 0) {
            fullName = name;
        } else {
            fullName = WIDGET_PACKAGE_NAME + '.' + name;
        }

        try {
            Map e = (Map) sConstructors.get();
            if (e == null) {
                e = new HashMap();
                sConstructors.set(e);
            }

            Constructor c = (Constructor) e.get(fullName);
            if (c == null) {
                Class clazz = Class.forName(fullName, true, context.getClassLoader());
                c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
                c.setAccessible(true);
                e.put(fullName, c);
            }

            return (Style) c.newInstance(context, attrs);
        } catch (Exception var7) {
            throw new RuntimeException("Could not inflate Style subclass " + fullName, var7);
        }
    }
}

From source file:org.hibernate.internal.util.ReflectHelper.java

/**
 * Retrieve the default (no arg) constructor from the given class.
 *
 * @param clazz The class for which to retrieve the default ctor.
 * @return The default constructor./*from  w ww  .jav a  2s .  c om*/
 * @throws PropertyNotFoundException Indicates there was not publicly accessible, no-arg constructor (todo : why PropertyNotFoundException???)
 */
public static <T> Constructor<T> getDefaultConstructor(Class<T> clazz) throws PropertyNotFoundException {
    if (isAbstractClass(clazz)) {
        return null;
    }

    try {
        Constructor<T> constructor = clazz.getDeclaredConstructor(NO_PARAM_SIGNATURE);
        constructor.setAccessible(true);
        return constructor;
    } catch (NoSuchMethodException nme) {
        throw new PropertyNotFoundException(
                "Object class [" + clazz.getName() + "] must declare a default (no-argument) constructor");
    }
}

From source file:org.apache.hama.util.ReflectionUtils.java

/**
 * Create an instance with corresponded class and object values supplied.
 * Constructor//from  w  ww. ja va 2 s.c  o m
 * 
 * @param theClass supplies instance to be created.
 * @param values are parameters applied when instance is created.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T newInstance(Class<T> theClass, Object[] values) {
    T result;
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (null == meth) {
            Class[] parameters = new Class[values.length];
            int idx = 0;
            for (Object value : values) {
                parameters[idx++] = value.getClass();
            }
            meth = theClass.getDeclaredConstructor(parameters);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance(values);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;

}