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.jnosql.artemis.reflection.Reflections.java

/**
 * Make the given a constructor class accessible, explicitly setting it accessible
 * if necessary. The setAccessible(true) method is only
 * called when actually necessary, to avoid unnecessary
 * conflicts with a JVM SecurityManager (if active).
 *
 * @param clazz the class constructor acessible
 * @throws ConstructorException when the constructor has public and default
 *///  w w  w.j  a  va  2  s . com
public Constructor makeAccessible(Class clazz) throws ConstructorException {
    List<Constructor> constructors = Stream.of(clazz.getDeclaredConstructors())
            .filter(c -> c.getParameterCount() == 0).collect(toList());

    if (constructors.isEmpty()) {
        throw new ConstructorException(clazz);
    }
    Optional<Constructor> publicConstructor = constructors.stream()
            .filter(c -> Modifier.isPublic(c.getModifiers())).findFirst();
    if (publicConstructor.isPresent()) {
        return publicConstructor.get();
    }

    Constructor constructor = constructors.get(0);
    constructor.setAccessible(true);
    return constructor;
}

From source file:com.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyCut(CutDescriptor cutDescriptor, Object[] arguments) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {/*  w w  w  .  j  av  a  2s .c o  m*/
            Cut cut = cutDescriptor.getCut();
            Field field = cutDescriptor.getField();
            Type fieldType = field.getGenericType();
            String fieldName = field.getName();

            field.setAccessible(true);

            Constructor<?> constructor = cutDescriptor.getConstructor();
            constructor.setAccessible(true);

            ResolvableType resolver = ResolvableType.forType(fieldType);

            Class rawType;

            if (resolver.hasGenerics()) {
                if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                    rawType = resolver.getRawClass();
                } else {
                    rawType = resolver.resolve();
                }
            } else {
                rawType = resolver.resolve();
            }

            Module module = testInstance.getClass().getDeclaredAnnotation(Module.class);

            GenericBeanDefinition bean = new GenericBeanDefinition();
            bean.setBeanClass(rawType);
            bean.setAutowireCandidate(false);
            bean.setScope(SCOPE_PROTOTYPE);
            bean.setPrimary(true);
            bean.setLazyInit(true);
            bean.setRole(RootBeanDefinition.ROLE_APPLICATION);
            bean.setAutowireMode(RootBeanDefinition.AUTOWIRE_NO);
            appContext.registerBeanDefinition(fieldName, bean);
            if (module != null) {
                appContext.register(module.value());
            }
            appContext.refresh();

            Object instance = appContext.getBean(fieldName, arguments);

            if (cut.value()) {
                instance = spy(instance);
            }

            field.set(testInstance, instance);

            return instance;
        } catch (SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:org.dspace.search.DSIndexer.java

/**
  * Get the Lucene analyzer to use according to current configuration (or
  * default). TODO: Should have multiple analyzers (and maybe indices?) for
  * multi-lingual DSpaces.//from  w  w w  .  j  a  v a  2  s .  co  m
  *
  * @return <code>Analyzer</code> to use
  * @throws IllegalStateException
  *             if the configured analyzer can't be instantiated
  */
static Analyzer getAnalyzer() {
    if (analyzer == null) {
        // We need to find the analyzer class from the configuration
        String analyzerClassName = ConfigurationManager.getProperty("search.analyzer");

        if (analyzerClassName == null) {
            // Use default
            analyzerClassName = "org.dspace.search.DSAnalyzer";
        }

        try {
            Class analyzerClass = Class.forName(analyzerClassName);
            Constructor constructor = analyzerClass.getDeclaredConstructor(Version.class);
            constructor.setAccessible(true);
            analyzer = (Analyzer) constructor.newInstance(luceneVersion);
        } catch (Exception e) {
            log.fatal(LogManager.getHeader(null, "no_search_analyzer", "search.analyzer=" + analyzerClassName),
                    e);

            throw new IllegalStateException(e.toString());
        }
    }

    return analyzer;
}

From source file:com.joyveb.dbpimpl.cass.prepare.option.DefaultOption.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean isCoerceable(Object value) {
    if (value == null || type == null) {
        return true;
    }//from w  w w  . ja  va  2 s  .c  o m

    // check map
    if (Map.class.isAssignableFrom(type)) {
        return Map.class.isAssignableFrom(value.getClass());
    }
    // check collection
    if (Collection.class.isAssignableFrom(type)) {
        return Collection.class.isAssignableFrom(value.getClass());
    }
    // check enum
    if (type.isEnum()) {
        try {
            String name = value instanceof Enum ? name = ((Enum) value).name() : value.toString();
            Enum.valueOf((Class<? extends Enum>) type, name);
            return true;
        } catch (NullPointerException x) {
            return false;
        } catch (IllegalArgumentException x) {
            return false;
        }
    }

    // check class via String constructor
    try {
        Constructor<?> ctor = type.getConstructor(String.class);
        if (!ctor.isAccessible()) {
            ctor.setAccessible(true);
        }
        ctor.newInstance(value.toString());
        return true;
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    } catch (IllegalArgumentException e) {
    } catch (InvocationTargetException e) {
    } catch (NoSuchMethodException e) {
    } catch (SecurityException e) {
    }
    return false;
}

From source file:org.blocks4j.reconf.client.constructors.SimpleConstructor.java

public Object construct(MethodData data) throws Throwable {
    Class<?> returnClass = (Class<?>) data.getReturnType();

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("'") || !trimmed.endsWith("'")) {
        throw new RuntimeException(msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }/*w w w.  j  a  v a  2s .  c  o  m*/

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);

    if (String.class.equals(returnClass)) {
        return wholeValue;
    }

    if (null == data.getValue()) {
        return null;
    }

    if (Object.class.equals(returnClass)) {
        returnClass = String.class;
    }

    if (char.class.equals(data.getReturnType()) || Character.class.equals(data.getReturnType())) {
        if (StringUtils.length(wholeValue) == 1) {
            return CharUtils.toChar(wholeValue);
        }
        return CharUtils.toChar(StringUtils.replace(wholeValue, " ", ""));
    }

    if (primitiveBoxing.containsKey(returnClass)) {
        if (StringUtils.isBlank(wholeValue)) {
            return null;
        }
        Method parser = primitiveBoxing.get(returnClass).getMethod(
                "parse" + StringUtils.capitalize(returnClass.getSimpleName()), new Class<?>[] { String.class });
        return parser.invoke(primitiveBoxing.get(returnClass), new Object[] { StringUtils.trim(wholeValue) });
    }

    Method valueOf = null;
    try {
        valueOf = returnClass.getMethod("valueOf", new Class<?>[] { String.class });
    } catch (NoSuchMethodException ignored) {
    }

    if (valueOf == null) {
        try {

            valueOf = returnClass.getMethod("valueOf", new Class<?>[] { Object.class });
        } catch (NoSuchMethodException ignored) {
        }
    }

    if (null != valueOf) {
        if (StringUtils.isEmpty(wholeValue)) {
            return null;
        }
        return valueOf.invoke(data.getReturnType(), new Object[] { StringUtils.trim(wholeValue) });
    }

    Constructor<?> constructor = null;

    try {
        constructor = returnClass.getConstructor(String.class);
        constructor.setAccessible(true);

    } catch (NoSuchMethodException ignored) {
        throw new IllegalStateException(
                msg.format("error.string.constructor", returnClass.getSimpleName(), data.getMethod()));
    }

    try {
        return constructor.newInstance(wholeValue);

    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof NumberFormatException) {
            return constructor.newInstance(StringUtils.trim(wholeValue));
        }
        throw e;
    }
}

From source file:reconf.client.constructors.SimpleConstructor.java

public Object construct(MethodData data) throws Throwable {
    if (data.hasAdapter()) {
        return data.getAdapter().adapt(data.getValue());
    }//from www . j  a v a 2s  .  c  o  m

    Class<?> returnClass = (Class<?>) data.getReturnType();

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("'") || !trimmed.endsWith("'")) {
        throw new RuntimeException(msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);

    if (String.class.equals(returnClass)) {
        return wholeValue;
    }

    if (null == data.getValue()) {
        return null;
    }

    if (Object.class.equals(returnClass)) {
        returnClass = String.class;
    }

    if (char.class.equals(data.getReturnType()) || Character.class.equals(data.getReturnType())) {
        if (StringUtils.length(wholeValue) == 1) {
            return CharUtils.toChar(wholeValue);
        }
        return CharUtils.toChar(StringUtils.replace(wholeValue, " ", ""));
    }

    if (primitiveBoxing.containsKey(returnClass)) {
        if (StringUtils.isBlank(wholeValue)) {
            return null;
        }
        Method parser = primitiveBoxing.get(returnClass).getMethod(
                "parse" + StringUtils.capitalize(returnClass.getSimpleName()), new Class<?>[] { String.class });
        return parser.invoke(primitiveBoxing.get(returnClass), new Object[] { StringUtils.trim(wholeValue) });
    }

    Method valueOf = null;
    try {
        valueOf = returnClass.getMethod("valueOf", new Class<?>[] { String.class });
    } catch (NoSuchMethodException ignored) {
    }

    if (valueOf == null) {
        try {

            valueOf = returnClass.getMethod("valueOf", new Class<?>[] { Object.class });
        } catch (NoSuchMethodException ignored) {
        }
    }

    if (null != valueOf) {
        if (StringUtils.isEmpty(wholeValue)) {
            return null;
        }
        return valueOf.invoke(data.getReturnType(), new Object[] { StringUtils.trim(wholeValue) });
    }

    Constructor<?> constructor = null;

    try {
        constructor = returnClass.getConstructor(String.class);
        constructor.setAccessible(true);

    } catch (NoSuchMethodException ignored) {
        throw new IllegalStateException(
                msg.format("error.string.constructor", returnClass.getSimpleName(), data.getMethod()));
    }

    try {
        return constructor.newInstance(wholeValue);

    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof NumberFormatException) {
            return constructor.newInstance(StringUtils.trim(wholeValue));
        }
        throw e;
    }
}

From source file:com.haulmont.cuba.core.config.ConfigDefaultMethod.java

@Override
public Object invoke(ConfigHandler handler, Object[] args, Object proxy) {
    try {/*from  ww w  . ja v  a2  s. c  o  m*/
        if (SystemUtils.IS_JAVA_1_8) {
            // hack to invoke default method of an interface reflectively
            Constructor<MethodHandles.Lookup> lookupConstructor = MethodHandles.Lookup.class
                    .getDeclaredConstructor(Class.class, Integer.TYPE);
            if (!lookupConstructor.isAccessible()) {
                lookupConstructor.setAccessible(true);
            }
            return lookupConstructor.newInstance(configInterface, MethodHandles.Lookup.PRIVATE)
                    .unreflectSpecial(configMethod, configInterface).bindTo(proxy).invokeWithArguments(args);
        } else {
            return MethodHandles.lookup()
                    .findSpecial(configInterface, configMethod.getName(),
                            MethodType.methodType(configMethod.getReturnType(),
                                    configMethod.getParameterTypes()),
                            configInterface)
                    .bindTo(proxy).invokeWithArguments(args);
        }
    } catch (Throwable throwable) {
        throw new RuntimeException("Error invoking default method of config interface", throwable);
    }
}

From source file:com.github.wnameless.jsonapi.JapisonTest.java

@Test
public void testPrivateConstruct() throws Exception {
    Constructor<JsonApi> c = JsonApi.class.getDeclaredConstructor();
    assertTrue(Modifier.isPrivate(c.getModifiers()));
    c.setAccessible(true);
    c.newInstance();//www.j a  v  a 2 s. co m
}

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);
    constructor.newInstance();/*from   w  w w.j av  a  2s  .  c om*/
}

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

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass, Configuration conf) {
    T result;//from   w  ww  . j  a v  a2 s .c  om
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (meth == null) {
            meth = theClass.getDeclaredConstructor(EMPTY_ARRAY);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}