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:com.linkedin.pinot.common.segment.fetcher.SegmentFetcherFactoryTest.java

License:asdf

@BeforeMethod
public void setUp() throws Exception {
    // Use reflection to get a new segment fetcher factory
    Constructor<SegmentFetcherFactory> constructor = SegmentFetcherFactory.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    _segmentFetcherFactory = constructor.newInstance();
}

From source file:org.datalorax.populace.core.populate.instance.DefaultConstructorInstanceFactory.java

private <T> Constructor<? extends T> getConstructor(final Class<? extends T> rawType,
        Class<?>... parameterTypes) {
    try {/*from w ww .j  a  va 2s . c o m*/
        final Constructor<? extends T> defaultConstructor = rawType.getDeclaredConstructor(parameterTypes);
        defaultConstructor.setAccessible(true);
        return defaultConstructor;
    } catch (NoSuchMethodException e) {
        final Constructor<?>[] constructors = rawType.getDeclaredConstructors();
        throw new PopulatorException(
                "Failed to instantiate type as no viable constructor could be found for type."
                        + " Either add a suitable constructor or consider adding a custom InstanceFactory to handle this type."
                        + "\n\tType: " + rawType + "\n\tRequired constructor arguments: "
                        + (parameterTypes.length == 0 ? "none" : StringUtils.join(parameterTypes, ','))
                        + "\n\tavailable Constructors: "
                        + (constructors.length == 0 ? "none" : StringUtils.join(constructors, ',')),
                e);
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

public static Constructor<?> getConstructor(Class<?> type, Class<?>[] parameterTypes) {
    try {//from w w w .  j av a2 s.  com
        Constructor<?> constructor = type.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        return constructor;
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.onosproject.yang.compiler.utils.io.impl.YangFileScannerTest.java

/**
 * A private constructor is tested.//from   w  w w  .  j  av  a 2  s. c om
 *
 * @throws SecurityException         if any security violation is observed
 * @throws NoSuchMethodException     if when the method is not found
 * @throws IllegalArgumentException  if there is illegal argument found
 * @throws InstantiationException    if instantiation is provoked for the private constructor
 * @throws IllegalAccessException    if instance is provoked or a method is provoked
 * @throws InvocationTargetException when an exception occurs by the method or constructor
 */
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    Class<?>[] classesToConstruct = { YangFileScanner.class };
    for (Class<?> clazz : classesToConstruct) {
        Constructor<?> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        assertThat(null, not(constructor.newInstance()));
    }
}

From source file:org.tynamo.model.elasticsearch.util.ReflectionUtil.java

/**
 * New instance.//  ww w.  j a v  a 2 s.co m
 * 
 * @param <T>
 *          the generic type
 * @param clazz
 *          the clazz
 * @return the t
 */
public static <T> T newInstance(Class<T> clazz) {
    Constructor<T> ctor = null;

    if (classConstructorCache.containsKey(clazz)) {
        ctor = (Constructor<T>) classConstructorCache.get(clazz);
    } else {
        // Try public ctor first
        try {
            ctor = clazz.getConstructor();
        } catch (Exception e) {
            // Swallow, no public ctor
        }

        // Next, try non-public ctor
        try {
            ctor = clazz.getDeclaredConstructor();
            ctor.setAccessible(true);
        } catch (Exception e) {
            // Swallow, no non-public ctor
        }

        classConstructorCache.put(clazz, ctor);
    }

    if (ctor != null) {
        try {
            return ctor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate " + clazz, e);
        }
    } else {
        throw new RuntimeException("No default constructor for " + clazz);
    }
}

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

/**
 * Retrieve a constructor for the given class, with arguments matching the specified Hibernate mapping
 * {@link Type types}.// www.j a  va  2s  .  co m
 *
 * @param clazz The class needing instantiation
 * @param types The types representing the required ctor param signature
 * @return The matching constructor.
 * @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor (todo : again with PropertyNotFoundException???)
 */
public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException {
    final Constructor[] candidates = clazz.getConstructors();
    for (int i = 0; i < candidates.length; i++) {
        final Constructor constructor = candidates[i];
        final Class[] params = constructor.getParameterTypes();
        if (params.length == types.length) {
            boolean found = true;
            for (int j = 0; j < params.length; j++) {
                final boolean ok = params[j].isAssignableFrom(types[j].getReturnedClass())
                        || (types[j] instanceof PrimitiveType
                                && params[j] == ((PrimitiveType) types[j]).getPrimitiveClass());
                if (!ok) {
                    found = false;
                    break;
                }
            }
            if (found) {
                constructor.setAccessible(true);
                return constructor;
            }
        }
    }
    throw new PropertyNotFoundException("no appropriate constructor in class: " + clazz.getName());
}

From source file:com.google.gwt.site.uploader.ResourceUploaderTest.java

private Key createKey() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SecurityException {
    Constructor<Key> declaredConstructor = Key.class.getDeclaredConstructor(new Class[0]);

    declaredConstructor.setAccessible(true);

    return declaredConstructor.newInstance();
}

From source file:com.qualogy.qafe.business.resource.java.JavaClass.java

private Object createInstance(Class<?> clazz, JavaResource resource) {
    Object instance = null;/*from w  w  w  .j  a  v a  2s.com*/
    try {
        //         List<Parameter> arguments = resource.getArguments();
        //         if(arguments!=null){
        //            Collections.sort(arguments);
        //            for (Parameter argument : arguments) {
        //               argument.get
        //            }
        //         }
        Constructor<?> constructor = clazz.getDeclaredConstructor(new Class[] {});
        constructor.setAccessible(true);
        instance = constructor.newInstance(new Object[] {});
    } catch (NoSuchMethodException e) {
        throw new ResourceInitializationException("possible error; no default constructor", e);
    } catch (InvocationTargetException e) {
        throw new ResourceInitializationException(e);
    } catch (IllegalAccessException e) {
        throw new ResourceInitializationException(e);
    } catch (InstantiationException e) {
        throw new ResourceInitializationException(e);
    }
    return instance;
}

From source file:cpcc.vvrte.services.task.AcoTspSimpleTest.java

@Test
public void shouldHavePrivateConstructor() throws Exception {
    Constructor<AcoTspSimple> cnt = AcoTspSimple.class.getDeclaredConstructor();
    assertFalse(cnt.isAccessible());//from w ww . j a va 2 s.  com
    cnt.setAccessible(true);
    cnt.newInstance();
}

From source file:org.projectforge.common.BeanHelper.java

public static Object newInstance(final Class<?> clazz) {
    Constructor<?> constructor = null;
    try {// w w w.ja  v  a  2s .c  om
        constructor = clazz.getDeclaredConstructor(new Class[0]);
    } catch (final SecurityException ex) {
        logInstantiationException(ex, clazz);
    } catch (final NoSuchMethodException ex) {
        logInstantiationException(ex, clazz);
    }
    if (constructor == null) {
        try {
            return clazz.newInstance();
        } catch (final InstantiationException ex) {
            logInstantiationException(ex, clazz);
        } catch (final IllegalAccessException ex) {
            logInstantiationException(ex, clazz);
        }
        return null;
    }
    constructor.setAccessible(true);
    try {
        return constructor.newInstance();
    } catch (final IllegalArgumentException ex) {
        logInstantiationException(ex, clazz);
    } catch (final InstantiationException ex) {
        logInstantiationException(ex, clazz);
    } catch (final IllegalAccessException ex) {
        logInstantiationException(ex, clazz);
    } catch (final InvocationTargetException ex) {
        logInstantiationException(ex, clazz);
    }
    return null;
}