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:org.polymap.core.runtime.DefaultSessionContext.java

public final <T> T sessionSingleton(final Class<T> type) {
    assert type != null;
    checkDestroyed();/*w  w  w .j a v  a2 s  .c  o  m*/
    try {
        T result = (T) attributes.get(type.getName());
        if (result == null) {

            // create an instance (without write lock)
            Constructor constructor = type.getDeclaredConstructor(new Class[] {});
            if (constructor.isAccessible()) {
                result = type.newInstance();
            } else {
                constructor.setAccessible(true);
                result = (T) constructor.newInstance(new Object[] {});
            }

            Object old = attributes.putIfAbsent(type.getName(), result);
            // as there is no lock we have to check after put what object was added actually
            result = old != null ? (T) old : result;
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.unitils.core.reflect.ClassWrapper.java

/**
 * Creates an instance of this class using the default (no-arg) constructor.
 * An exception is raised when there is no such constructor
 *
 * @return An instance of this type, not null
 *//*from   w w w  . j a  v  a 2  s . co  m*/
public Object createInstance() {
    if (wrappedClass.isMemberClass() && !isStatic(wrappedClass.getModifiers())) {
        throw new UnitilsException("Unable to create instance of type " + getName()
                + ". Type is a non-static inner class which is only know in the context of an instance of the enclosing class. Declare the inner class static to make construction possible.");
    }
    try {
        Constructor<?> constructor = wrappedClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();

    } catch (NoSuchMethodException e) {
        throw new UnitilsException("Unable to create instance of type " + getName()
                + ". No default (no-argument) constructor found.", e);

    } catch (InstantiationException e) {
        throw new UnitilsException(
                "Unable to create instance of type " + getName() + ". Type is an abstract class.", e);

    } catch (Exception e) {
        Throwable cause = (e instanceof InvocationTargetException) ? e.getCause() : e;
        throw new UnitilsException("Unable to create instance of type " + getName() + ".", cause);
    }
}

From source file:com.balch.android.app.framework.preference.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {/*from ww  w  .ja  v a 2s.c o  m*/
        Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class,
                int.class);
        c.setAccessible(true);
        mPreferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
    } catch (Exception e) {
    }
}

From source file:org.openo.nfvo.resmanagement.common.util.request.RequestUtilTest.java

@Test
public void testPrivateConstructor() throws Exception {
    Constructor constructor = RequestUtil.class.getDeclaredConstructor();
    assertTrue("Constructor is  private", Modifier.isPrivate(constructor.getModifiers()));

    constructor.setAccessible(true);
    constructor.newInstance();/*from  www.j a va2s  .co  m*/
}

From source file:com.taobao.weex.devtools.json.ObjectMapper.java

private <T> T _convertFromJSONObject(JSONObject jsonObject, Class<T> type) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException, JSONException {
    Constructor<T> constructor = type.getDeclaredConstructor((Class[]) null);
    constructor.setAccessible(true);
    T instance = constructor.newInstance();
    Field[] fields = type.getFields();
    for (int i = 0; i < fields.length; ++i) {
        Field field = fields[i];//w  ww  . j ava  2  s .co  m
        Object value = jsonObject.opt(field.getName());
        Object setValue = getValueForField(field, value);
        try {
            field.set(instance, setValue);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Class: " + type.getSimpleName() + " " + "Field: "
                    + field.getName() + " type " + setValue.getClass().getName(), e);
        }
    }
    return instance;
}

From source file:jahirfiquitiva.iconshowcase.fragments.base.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {/*from ww w .  jav a 2 s .com*/
        Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class,
                int.class);
        c.setAccessible(true);
        mPreferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
    } catch (Exception ignored) {
    }
}

From source file:jenkins.security.apitoken.ApiTokenStatsTest.java

private ApiTokenStats.SingleTokenStats createSingleTokenStatsByReflection(String uuid, String dateString,
        Integer counter) throws Exception {
    Class<ApiTokenStats.SingleTokenStats> clazz = ApiTokenStats.SingleTokenStats.class;
    Constructor<ApiTokenStats.SingleTokenStats> constructor = clazz.getDeclaredConstructor(String.class);
    constructor.setAccessible(true);

    ApiTokenStats.SingleTokenStats result = constructor.newInstance(uuid);

    {//from  w  w  w . j ava2 s  .c  om
        Field field = clazz.getDeclaredField("useCounter");
        field.setAccessible(true);
        field.set(result, counter);
    }
    if (dateString != null) {
        Field field = clazz.getDeclaredField("lastUseDate");
        field.setAccessible(true);
        field.set(result, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(dateString));
    }

    return result;
}

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);
    constructor.newInstance();//from w  ww  .  j  a va2 s.  co  m
}

From source file:eu.inmite.apps.smsjizdenka.framework.fragment.PreferenceListFragment.java

/**
 * Creates the {@link PreferenceManager}.
 *
 * @return The {@link PreferenceManager} used by this activity.
 *//*from  www . j a va  2 s.c om*/
private PreferenceManager onCreatePreferenceManager() {
    try {
        Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class,
                int.class);
        c.setAccessible(true);
        PreferenceManager preferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
        return preferenceManager;
    } catch (Exception e) {
        DebugLog.wtf("PreferenceListFragment.onCreatePreferenceManager() - failed", e);
        return null;
    }
}

From source file:net.krotscheck.util.ResourceUtilTest.java

/**
 * Ensure the constructor is private.//from  ww w. jav  a  2 s .co  m
 *
 * @throws Exception Tests throw exceptions.
 */
@Test
public void testConstructorIsPrivate() throws Exception {
    Constructor<ResourceUtil> constructor = ResourceUtil.class.getDeclaredConstructor();
    Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));

    // Override the private constructor and create an instance
    constructor.setAccessible(true);
    ResourceUtil util = constructor.newInstance();
    Assert.assertNotNull(util);
}