Example usage for java.lang.reflect Method setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.flowpowered.cerealization.config.annotated.AnnotatedObjectConfiguration.java

private void invokeMethods(Set<Method> methods, Object target, ConfigurationNode nodeParam)
        throws ConfigurationException {
    for (Method method : methods) {
        method.setAccessible(true);
        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length == 0 || !ConfigurationNode.class.isAssignableFrom(parameters[0])) {
            continue;
        }/*  w w  w .j a v a2  s. com*/
        try {
            method.invoke(target, nodeParam);
        } catch (IllegalAccessException ex) {
            throw new ConfigurationException(ex);
        } catch (InvocationTargetException ex) {
            throw new ConfigurationException(ex);
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractTypeAwareCheckTest.java

@Test
public void testClassRegularClass() throws Exception {
    Class<?> tokenType = Class.forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$Token");

    Class<?> regularClassType = Class
            .forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$RegularClass");
    Constructor<?> regularClassConstructor = regularClassType.getDeclaredConstructor(tokenType, String.class,
            AbstractTypeAwareCheck.class);
    regularClassConstructor.setAccessible(true);

    try {//from   w  w w  .ja v a2 s . co m
        regularClassConstructor.newInstance(null, "", new JavadocMethodCheck());
    } catch (InvocationTargetException ex) {
        assertTrue(ex.getCause() instanceof IllegalArgumentException);
        assertEquals("ClassInfo's name should be non-null", ex.getCause().getMessage());
    }

    Constructor<?> tokenConstructor = tokenType.getDeclaredConstructor(String.class, int.class, int.class);
    Object token = tokenConstructor.newInstance("blablabla", 1, 1);

    Object regularClass = regularClassConstructor.newInstance(token, "sur", new JavadocMethodCheck());

    Method toString = regularClass.getClass().getDeclaredMethod("toString");
    toString.setAccessible(true);
    String result = (String) toString.invoke(regularClass);
    assertEquals("RegularClass[name=Token[blablabla(1x1)], in class=sur, loadable=true," + " class=null]",
            result);

    Method setClazz = regularClass.getClass().getDeclaredMethod("setClazz", Class.class);
    setClazz.setAccessible(true);
    Class<?> arg = null;
    setClazz.invoke(regularClass, arg);

    Method getClazz = regularClass.getClass().getDeclaredMethod("getClazz");
    getClazz.setAccessible(true);
    assertNull(getClazz.invoke(regularClass));
}

From source file:by.creepid.docsreporter.converter.images.ImageConverterImplTest.java

public ImageConverterImplTest() {
    instance = new ImageConverterImpl();

    try {/*w  w  w. ja v  a  2 s  .c o m*/
        Method initMethod = ImageConverterImpl.class.getDeclaredMethod("addCMYKServiceProvider");
        initMethod.setAccessible(true);
        ReflectionUtils.invokeMethod(initMethod, instance);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.app.test.util.CategoryUtilTest.java

@Test
public void testIsNewerCategoryVersion() throws Exception {
    ReleaseUtil.addRelease(_CATEGORY_RELEASE_NAME, "100");

    Method method = _clazz.getDeclaredMethod("_isNewerCategoryVersion", String.class);

    method.setAccessible(true);

    Assert.assertFalse((boolean) method.invoke(_classInstance, ""));
    Assert.assertFalse((boolean) method.invoke(_classInstance, "1"));
    Assert.assertFalse((boolean) method.invoke(_classInstance, "100"));
    Assert.assertTrue((boolean) method.invoke(_classInstance, "200"));
}

From source file:com.adito.server.jetty.TunnelAdapter.java

private void setSocketTimeout(Object obj, int timeoutMs) {

    if (log.isDebugEnabled())
        log.debug("Looking for com.sun.net.ssl.internal.ssl.SSLSocketImpl to set timeout");

    Object ssl = getPrivateMember(obj, "com.sun.net.ssl.internal.ssl.SSLSocketImpl");

    if (ssl != null) {
        try {//w ww . j  a v  a 2s.  com
            Method m = ssl.getClass().getMethod("setSoTimeout", new Class[] { int.class });
            if (m != null) {
                m.setAccessible(true);
                m.invoke(ssl, new Object[] { timeoutMs });

                if (log.isDebugEnabled())
                    log.debug("Configured socket timeout on tunnel of " + timeoutMs + "ms");
            } else {
                if (log.isInfoEnabled())
                    log.warn("Could not configure a timeout on socket! no setSoTimeout available");
            }
        } catch (Throwable t) {
            log.error("Could not access setSoTimeout method", t);
        }
    } else {
        if (log.isInfoEnabled())
            log.warn("Could not configure a timeout on socket! no SSLSocketImpl available");
    }
}

From source file:com.netflix.lipstick.adaptors.LOJsonAdaptorTest.java

private LogicalPlan getLogicalPlan(LipstickPigServer lps) throws Exception {
    Field f = lps.getClass().getSuperclass().getDeclaredField("currDAG");
    f.setAccessible(true);//from   w w  w  .  ja  v  a2s  .c o m

    Object graph = f.get(lps);
    Method buildPlanMethod = graph.getClass().getDeclaredMethod("buildPlan", String.class);
    buildPlanMethod.setAccessible(true);
    buildPlanMethod.invoke(graph, new Object[] { null });
    Method getPlanMethod = graph.getClass().getMethod("getPlan", String.class);

    return (LogicalPlan) getPlanMethod.invoke(graph, new Object[] { null });
}

From source file:com.netflix.hystrix.contrib.javanica.command.HystrixCommandBuilderFactory.java

private CommandAction createFallbackAction(MetaHolder metaHolder) {

    FallbackMethod fallbackMethod = MethodProvider.getInstance().getFallbackMethod(
            metaHolder.getObj().getClass(), metaHolder.getMethod(), metaHolder.isExtendedFallback());
    fallbackMethod.validateReturnType(metaHolder.getMethod());
    CommandAction fallbackAction = null;
    if (fallbackMethod.isPresent()) {

        Method fMethod = fallbackMethod.getMethod();
        if (fallbackMethod.isCommand()) {
            fMethod.setAccessible(true);
            HystrixCommand hystrixCommand = fMethod.getAnnotation(HystrixCommand.class);
            MetaHolder fmMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(fMethod)
                    .ajcMethod(getAjcMethod(metaHolder.getObj(), fMethod)).args(metaHolder.getArgs())
                    .fallback(true).defaultCollapserKey(metaHolder.getDefaultCollapserKey())
                    .fallbackMethod(fMethod).extendedFallback(fallbackMethod.isExtended())
                    .fallbackExecutionType(fallbackMethod.getExecutionType())
                    .extendedParentFallback(metaHolder.isExtendedFallback())
                    .observable(ExecutionType.OBSERVABLE == fallbackMethod.getExecutionType())
                    .defaultCommandKey(fMethod.getName()).defaultGroupKey(metaHolder.getDefaultGroupKey())
                    .defaultThreadPoolKey(metaHolder.getDefaultThreadPoolKey())
                    .defaultProperties(metaHolder.getDefaultProperties().orNull())
                    .hystrixCollapser(metaHolder.getHystrixCollapser())
                    .observableExecutionMode(hystrixCommand.observableExecutionMode())
                    .hystrixCommand(hystrixCommand).build();
            fallbackAction = new LazyCommandExecutionAction(fmMetaHolder);
        } else {/*  ww  w .  ja  v  a 2 s. c o m*/
            MetaHolder fmMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(fMethod)
                    .fallbackExecutionType(ExecutionType.SYNCHRONOUS)
                    .extendedFallback(fallbackMethod.isExtended())
                    .extendedParentFallback(metaHolder.isExtendedFallback()).ajcMethod(null) // if fallback method isn't annotated with command annotation then we don't need to get ajc method for this
                    .args(metaHolder.getArgs()).build();

            fallbackAction = new MethodExecutionAction(fmMetaHolder.getObj(), fMethod, fmMetaHolder.getArgs(),
                    fmMetaHolder);
        }

    }
    return fallbackAction;
}

From source file:com.lrs.mvc.DispatcherManager.java

public void handleInterceptor(Object controller, Class<? extends Annotation> annotationClass) {
    Method method = ReflectionUtils.findMethod(controller.getClass(), annotationClass);
    if (method != null) {
        method.setAccessible(true);
        log.debug(String.format("Invoking Interceptor[start] %s Method: %s ", annotationClass.getName(),
                method.getName()));/*from   w w  w.j ava  2s.c  om*/
        ReflectionUtils.invokeMethod(method, controller);
        log.debug(String.format("Invoking Interceptor[end] %s Method: %s ", annotationClass.getName(),
                method.getName()));
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheckTest.java

@Test
public void testWrongSeparatorLength() throws Exception {
    NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck();
    final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class);
    check.configure(checkConfig);//from ww  w . ja  v  a  2  s.c o  m

    Method method = NewlineAtEndOfFileCheck.class.getDeclaredMethod("endsWithNewline", RandomAccessFile.class);
    method.setAccessible(true);
    RandomAccessFile file = mock(RandomAccessFile.class);
    when(file.length()).thenReturn(2000000L);
    try {
        method.invoke(new NewlineAtEndOfFileCheck(), file);
    } catch (InvocationTargetException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) {
            assertEquals("Unable to read 2 bytes, got 0", ex.getCause().getMessage());
        } else {
            assertEquals("Unable to read 1 bytes, got 0", ex.getCause().getMessage());
        }
    }
}

From source file:org.springmodules.cache.config.CacheNamespaceHandlerTests.java

private BeanDefinitionParser findParserForElement(String elementName) throws Exception {
    Method findParserForElementMethod = NamespaceHandlerSupport.class.getDeclaredMethod("findParserForElement",
            new Class[] { Element.class });

    findParserForElementMethod.setAccessible(true);
    return (BeanDefinitionParser) findParserForElementMethod.invoke(handler,
            new Object[] { new DomElementStub(elementName) });
}