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.bremersee.common.exception.ExceptionRegistry.java

private static Throwable findThrowableByMessageAndCause(final Class<? extends Throwable> clazz,
        final String message, final Throwable cause) {
    try {// w  w  w.jav  a 2s  . co m
        Constructor<? extends Throwable> constructor = clazz.getDeclaredConstructor(String.class,
                Throwable.class);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        return constructor.newInstance(message, cause);

    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException // NOSONAR
            | InvocationTargetException e) { // NOSONAR
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding throwable by message and cause failed. Class [" + clazz.getName() // NOSONAR
                    + "] has no suitable constructor: " + e.getMessage() // NOSONAR
                    + " (" + e.getClass().getName() + ")."); // NOSONAR
        }
        return null;
    }
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).//  ww w .  j a v  a 2  s. c  om
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
            && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}

From source file:au.id.hazelwood.xmltvguidebuilder.utils.ClassPathResourceUtilsUnitTest.java

@Test
public void testConstructor() throws Exception {
    Constructor<ClassPathResourceUtils> constructor = ClassPathResourceUtils.class.getDeclaredConstructor();
    assertFalse(constructor.isAccessible());
    ReflectionUtils.makeAccessible(constructor);
    assertNotNull(constructor.newInstance());
}

From source file:au.id.hazelwood.xmltvguidebuilder.utils.DateTimeUtilsUnitTest.java

@Test
public void testConstructor() throws Exception {
    Constructor<DateTimeUtils> constructor = DateTimeUtils.class.getDeclaredConstructor();
    assertFalse(constructor.isAccessible());
    ReflectionUtils.makeAccessible(constructor);
    assertNotNull(constructor.newInstance());
}

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

@Test
public void shouldHavePrivateConstructor() throws Exception {
    Constructor<AcoTspSimple> cnt = AcoTspSimple.class.getDeclaredConstructor();
    assertFalse(cnt.isAccessible());
    cnt.setAccessible(true);//w w  w.  ja  va  2  s. c  om
    cnt.newInstance();
}

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

public static Object newInstance(final Constructor<?> cstruct, final Object[] args) {
    boolean flag = cstruct.isAccessible();
    try {//from   w  w w  .j  a  v  a 2  s.  com
        cstruct.setAccessible(true);
        Object result = cstruct.newInstance(args);
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        cstruct.setAccessible(flag);
    }
}

From source file:com.fondesa.lyra.coder.DefaultCoderRetriever.java

/**
 * Retrieve a {@link StateCoder} from an annotation and the annotated class.
 *
 * @param saveState           annotation obtained from the annotated field
 * @param annotatedFieldClass java class of the annotate field
 * @return not null coder used to serialize and deserialize the state {@link Bundle}
 * @throws CoderNotFoundException if the coder can't be found or is unsupported
 *///w  ww . ja  v  a 2 s.  c  o m
@NonNull
@Override
public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass)
        throws CoderNotFoundException {
    StateCoder stateCoder;
    // Get the coder class from the annotation.
    final Class<? extends StateCoder> stateSDClass = saveState.value();
    if (stateSDClass == StateCoder.class) {
        // Get the coder from cache, if present.
        stateCoder = mCachedCoders.get(annotatedFieldClass);
        if (stateCoder != null)
            return stateCoder;

        // Get the coder if it's supported by default or throw a new CoderNotFoundException.
        stateCoder = StateCoderUtils.getBasicCoderForClass(annotatedFieldClass);
        // Put the coder in cache.
        mCachedCoders.put(annotatedFieldClass, stateCoder);
    } else {
        // A custom coder won't be cached to support multiple implementations for the same class.
        try {
            Constructor<? extends StateCoder> constructor = stateSDClass.getConstructor();
            boolean accessible = constructor.isAccessible();
            // If the constructor can't be accessed, it will be modified in accessible and will return inaccessible after.
            if (!accessible) {
                constructor.setAccessible(true);
            }
            // Creates the instance.
            stateCoder = constructor.newInstance();
            if (!accessible) {
                constructor.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate a " + StateCoder.class.getSimpleName() + " of class "
                    + stateSDClass.getName());
        }
    }
    return stateCoder;
}

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

@Override
public Object invoke(ConfigHandler handler, Object[] args, Object proxy) {
    try {/*from w  w  w.j  a  v  a 2s .  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.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. j  a va  2  s.  com*/

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

public final <T> T sessionSingleton(final Class<T> type) {
    assert type != null;
    checkDestroyed();//from   w  ww .ja va2 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);
    }
}