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:gov.nih.nci.caarray.util.CaArrayUtils.java

/**
 * For given class, returns a ReflectionHelper instance with property accessors for the class.
 * /* w  w w.  j  a v  a 2s . c  o m*/
 * @param clazz the class
 * @return the ReflectionHelper
 */
public static ReflectionHelper createReflectionHelper(Class<?> clazz) {
    final List<PropertyAccessor> accessors = new ArrayList<PropertyAccessor>();

    Class<?> currentClass = clazz;
    while (currentClass != null) {
        final Method[] methods = currentClass.getDeclaredMethods();
        for (final Method getter : methods) {
            if (getter.getName().startsWith("get") && getter.getParameterTypes().length == 0) {
                for (final Method setter : methods) {
                    if (setter.getName().equals('s' + getter.getName().substring(1))
                            && setter.getParameterTypes().length == 1
                            && Void.TYPE.equals(setter.getReturnType())
                            && getter.getReturnType().equals(setter.getParameterTypes()[0])) {
                        getter.setAccessible(true);
                        setter.setAccessible(true);
                        accessors.add(new PropertyAccessor(getter, setter));
                    }
                }
            }
        }

        currentClass = currentClass.getSuperclass();
    }

    return new ReflectionHelper(accessors.toArray(new PropertyAccessor[accessors.size()]));
}

From source file:iqq.app.core.service.impl.TaskServiceImpl.java

@Override
public void submit(final Object target, final String method, final Object... args) {
    threads.submit(new Runnable() {
        public void run() {
            for (Method m : target.getClass().getDeclaredMethods()) {
                if (m.getName().equals(method)) {
                    try {
                        if (!m.isAccessible()) {
                            m.setAccessible(true);
                        }//from w w  w.  java  2  s  .  c  o m
                        m.invoke(target, args);
                        return;
                    } catch (Throwable e) {
                        LOG.warn("invoke method error!!", e);
                    }
                }
            }
        }
    });
}

From source file:de.thkwalter.et.ortskurve.OrtskurveControllerTest.java

/**
 * Test fr die Methode {@link OrtskurveController#messpunkteValidieren(Vector2D[])}.
 * //from w w w. j  av  a 2  s .c om
 * @throws Throwable 
 */
@Test(expected = ApplicationRuntimeException.class)
public void testMesspunkteValidieren1() throws Throwable {
    // Die in diesem Test verwendeten Messpunkte werden erzeugt.
    Vector2D[] testMesspunkte = new Vector2D[] { new Vector2D(1.0, 0.0), new Vector2D(3.0, 0.0),
            new Vector2D(1, 0) };

    try {
        // Die zu testende Methode wird aufgerufen.
        Method methode = OrtskurveController.class.getDeclaredMethod("messpunkteValidieren", Vector2D[].class);
        methode.setAccessible(true);
        methode.invoke(this.ortskurveController, (Object) testMesspunkte);
    }

    // Die InvocationTargetException wird gefangen und die ursprngliche Ausnahme weitergeworfen.
    catch (InvocationTargetException invocationTargetException) {
        throw invocationTargetException.getCause();
    }
}

From source file:com.spectralogic.ds3client.metadata.WindowsMetadataRestore_Test.java

@Test
public void restorePermissions_Test() throws NoSuchMethodException, IOException, URISyntaxException,
        InvocationTargetException, IllegalAccessException, InterruptedException {
    final ImmutableMap.Builder<String, String> mMetadataMap = new ImmutableMap.Builder<>();
    final WindowsMetadataStore windowsMetadataStore = new WindowsMetadataStore(mMetadataMap);
    final Class aClass = WindowsMetadataStore.class;
    final Method method = aClass.getDeclaredMethod("saveFlagMetaData", new Class[] { Path.class });
    method.setAccessible(true);

    final File file = ResourceUtils.loadFileResource(FILE_NAME).toFile();

    method.invoke(windowsMetadataStore, file.toPath());

    final Method methodWindowsfilePermissions = aClass.getDeclaredMethod("saveWindowsfilePermissions",
            new Class[] { Path.class });
    methodWindowsfilePermissions.setAccessible(true);
    methodWindowsfilePermissions.invoke(windowsMetadataStore, file.toPath());

    final Set<String> mapKeys = mMetadataMap.build().keySet();
    final int keySize = mapKeys.size();
    final BasicHeader basicHeader[] = new BasicHeader[keySize + 1];
    basicHeader[0] = new BasicHeader(METADATA_PREFIX + MetadataKeyConstants.KEY_OS, localOS);
    int count = 1;
    for (final String key : mapKeys) {
        basicHeader[count] = new BasicHeader(key, mMetadataMap.build().get(key));
        count++;/*from www.j  a v a  2  s. c  om*/
    }

    final Metadata metadata = genMetadata(basicHeader);
    final WindowsMetadataRestore windowsMetadataRestore = new WindowsMetadataRestore(metadata, file.getPath(),
            MetaDataUtil.getOS());
    windowsMetadataRestore.restoreOSName();
    windowsMetadataRestore.restorePermissions();
}

From source file:org.openmrs.module.webservices.helper.ModuleFactoryWrapper.java

/**
 * It's hacky method to workaround the fact that before 2.x platform
 * {@link WebModuleUtil#stopModule(Module, ServletContext, boolean)} was private. It is
 * essential to support uploading modules 1.x platform via REST api
 *///from   w ww. j  a v a  2s.  c  o m
public void stopModuleSkipRefresh(Module module, ServletContext servletContext) {
    ModuleFactory.stopModule(module);
    try {
        Method stopModule = WebModuleUtil.class.getDeclaredMethod("stopModule", Module.class,
                ServletContext.class, Boolean.TYPE);
        stopModule.setAccessible(true);
        stopModule.invoke(null, module, servletContext, true);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e);
    }
}

From source file:org.vaadin.spring.i18n.Translator.java

private void translatedMethods(Locale locale, MessageSource messageSource) {
    for (Map.Entry<TranslatedProperty, Method> methodEntry : translatedMethods.entrySet()) {
        final Method method = methodEntry.getValue();
        final TranslatedProperty annotation = methodEntry.getKey();
        method.setAccessible(true);
        Object methodValue;/* w  w  w  .java2  s.  c o  m*/
        try {
            methodValue = method.invoke(target);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Could not access method " + method.getName());
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Could not invoke method " + method.getName(), e);
        }
        if (methodValue != null) {
            setPropertyValue(methodValue, annotation.property(),
                    messageSource.getMessage(annotation.key(), null, annotation.defaultValue(), locale));
        }
    }
}

From source file:com.brienwheeler.svc.authorize_net.impl.AbstractSvcAuthorizeNetTest.java

protected String createErrorMessage(Result<Transaction> result) throws Exception {
    CIMClientService target = AopTestUtils.getTarget(cimClientService);
    Method createErrorMessageMethod = CIMClientService.class.getDeclaredMethod("createErrorMessage",
            Result.class);
    createErrorMessageMethod.setAccessible(true);
    return (String) createErrorMessageMethod.invoke(target, result);
}

From source file:com.graphaware.server.foundation.bootstrap.GraphAwareBootstrappingFilter.java

protected final void addDefaultFilters(ServletContextHandler context) {
    //dirty dirty stuff
    try {//from  w  w w . j  a  v  a 2  s.c om
        Method m = Jetty9WebServer.class.getDeclaredMethod("addFiltersTo", ServletContextHandler.class);
        m.setAccessible(true);
        m.invoke(webServer, context);
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:jp.terasoluna.fw.beans.jxpath.JXPATH152PatchActivatorTest.java

/**
 * testActivate01() <br>/* ww w. j av a 2  s  .c om*/
 * <br>
 * () <br>
 * A <br>
 * <br>
 * () ?<br>
 * () JXPathIntrospector.byClasst:HashMap<br>
 * () JXPathIntrospector.byInterface:HashMap<br>
 * <br>
 * () JXPathIntrospector.byClass?HashMapForJXPathIntrospector?????<br>
 * () JXPathIntrospector.byInterface?HashMapForJXPathIntrospector?????<br>
 * () :INFO<br>
 * JXPATH-152 Patch activation succeeded.<br>
 * <br>
 * ??????? JXPathIntrospector?byClass?byInterface?HashMapForJXPathIntrospector???????? <br>
 * @throws Exception ?????
 */
@Test
public void testActivate01() throws Exception {
    // ??
    Field field = JXPathIntrospector.class.getDeclaredField("byClass");
    field.setAccessible(true);
    field.set(JXPathIntrospector.class, new HashMap<Object, Object>());
    field = JXPathIntrospector.class.getDeclaredField("byInterface");
    field.setAccessible(true);
    field.set(JXPathIntrospector.class, new HashMap<Object, Object>());

    // 
    Method method = JXPATH152PatchActivator.class.getDeclaredMethod("activate");
    method.setAccessible(true);
    method.invoke(JXPATH152PatchActivator.class);

    // 
    assertThat(logger.getLoggingEvents(), is(asList(info("JXPATH-152 Patch activation succeeded."))));
    field = JXPathIntrospector.class.getDeclaredField("byClass");
    field.setAccessible(true);
    assertTrue(
            ((Map<?, ?>) field.get(JXPathIntrospector.class)).getClass() == HashMapForJXPathIntrospector.class);
    field = JXPathIntrospector.class.getDeclaredField("byInterface");
    field.setAccessible(true);
    assertTrue(
            ((Map<?, ?>) field.get(JXPathIntrospector.class)).getClass() == HashMapForJXPathIntrospector.class);
}

From source file:com.amazonaws.http.conn.ssl.SdkTLSSocketFactory.java

/**
 * Double check the master secret of an SSL session must not be null, or
 * else a {@link SecurityException} will be thrown.
 * @param sock connected socket//from   ww w. j av a 2s.com
 */
private void verifyMasterSecret(final Socket sock) {
    if (sock instanceof SSLSocket) {
        SSLSocket ssl = (SSLSocket) sock;
        SSLSession session = ssl.getSession();
        if (session != null) {
            String className = session.getClass().getName();
            if ("sun.security.ssl.SSLSessionImpl".equals(className)) {
                try {
                    Class<?> clazz = Class.forName(className);
                    Method method = clazz.getDeclaredMethod("getMasterSecret");
                    method.setAccessible(true);
                    Object masterSecret = method.invoke(session);
                    if (masterSecret == null) {
                        session.invalidate();
                        if (log.isDebugEnabled()) {
                            log.debug("Invalidated session " + session);
                        }
                        throw log(new SecurityException("Invalid SSL master secret"));
                    }
                } catch (ClassNotFoundException e) {
                    failedToVerifyMasterSecret(e);
                } catch (NoSuchMethodException e) {
                    failedToVerifyMasterSecret(e);
                } catch (IllegalAccessException e) {
                    failedToVerifyMasterSecret(e);
                } catch (InvocationTargetException e) {
                    failedToVerifyMasterSecret(e.getCause());
                }
            }
        }
    }
    return;
}