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:de.thkwalter.et.schlupfbezifferung.SchlupfresiduumTest.java

/**
 * Test der Methode {@link Schlupfresiduum#xKomponentenSchnittpunktBerechnen(double)} fr den Fall, dass der 
 * Steigungswinkel gleich pi ist.//from  w  ww.  j  a va2s. com
 * 
 * @throws SecurityException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalArgumentException 
 * @throws IllegalAccessException 
 */
@Test
public void testXKomponentenSchnittpunktBerechnen_pi() throws NoSuchMethodException, SecurityException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // Der in diesem Test verwendete Steigungswinkel der Schlupfgeraden wird definiert.
    double phi = Math.PI * (1.0 + 1.0E-7);

    // Die zu testende Methode wird aufgerufen.
    Method methode = Schlupfresiduum.class.getDeclaredMethod("xKomponentenSchnittpunktBerechnen", double.class);
    methode.setAccessible(true);
    double[] xKomponentenSchnittpunkte = (double[]) methode.invoke(this.schlupfresiduum, phi);

    // Es wird berprft, ob die x-Komponenten der Schnittpunkte der Schlupfgeraden mit den Strahlen vom 
    // Inversionszentrum zu den Betriebspunkten korrekt berechnet worden sind.
    assertEquals(3, xKomponentenSchnittpunkte.length);
    assertEquals(this.testDrehpunktSchlupfgerade.getX(), xKomponentenSchnittpunkte[0], 0.0);
    assertEquals(this.testDrehpunktSchlupfgerade.getX(), xKomponentenSchnittpunkte[1], 0.0);
    assertEquals(this.testDrehpunktSchlupfgerade.getX(), xKomponentenSchnittpunkte[2], 0.0);
}

From source file:com.github.pith.typedconfig.TypedConfigPlugin.java

private Map<Class<Object>, Object> initConfigClasses(Collection<Class<?>> configClasses,
        Configuration configuration) {
    Map<Class<Object>, Object> configClassesMap = new HashMap<Class<Object>, Object>();

    for (Class<?> configClass : configClasses) {
        try {/*from   w  ww  .jav  a 2  s .  c  o  m*/
            Object configObject = configClass.newInstance();
            for (Method method : configClass.getDeclaredMethods()) {
                if (method.getName().startsWith("get")) {
                    Object property = configuration.getProperty(configClass.getSimpleName().toLowerCase()
                            + method.getName().substring(3).toLowerCase());
                    if (property != null) {
                        try {
                            Method setter = configClass.getDeclaredMethod("set" + method.getName().substring(3),
                                    method.getReturnType());
                            setter.setAccessible(true);
                            setter.invoke(configObject, property);
                        } catch (NoSuchMethodException e) {
                            throw new IllegalStateException("The TypedConfigPlugin can't initialize "
                                    + method.getName() + " because there is no associated setter.");
                        } catch (InvocationTargetException e) {
                            if (e.getCause() != null) {
                                throw new IllegalStateException("Failed to initialize " + method.getName(),
                                        e.getCause());
                            }
                        }
                    }
                }
            }
            //noinspection unchecked
            configClassesMap.put((Class<Object>) configClass, configObject);
        } catch (InstantiationException e) {
            throw new IllegalStateException("Failed to instantiate " + configClass, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Failed to access the constructor of " + configClass, e.getCause());
        }
    }
    return configClassesMap;
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}/* ww  w  .  jav  a  2s  .  c o m*/
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testVersion() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    CliParser parser = new CliParser();
    Method help = parser.getClass().getDeclaredMethod("printVersion");
    help.setAccessible(true);
    help.invoke(parser);/*from   w  ww  .j  a  v a2s . c om*/
}

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

/**
 * Test fr die Methode {@link OrtskurveController#ortskurveBestimmen(Vector2D[], double[])}.
 * @throws SecurityException //w  ww  .ja va2 s. c o m
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalArgumentException 
 * @throws IllegalAccessException 
 */
@Test
public void testOrtskurveBestimmen() throws NoSuchMethodException, SecurityException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    // Die in diesem Test verwendeten Messpunkte werden deklariert.
    Vector2D[] testMesspunkte = new Vector2D[] { new Vector2D(2.0, 0.0), new Vector2D(3.0, 1.0),
            new Vector2D(3.0, -1.0) };

    // Der in diesem Test verwendete Startpunkt wird deklariert.
    double[] testStartpunkt = new double[] { 3.0, 0.0, 1.0 };

    // Die zu testenden Methode wird aufgerufen.
    Method methode = OrtskurveController.class.getDeclaredMethod("ortskurveBestimmen", Vector2D[].class,
            double[].class);
    methode.setAccessible(true);
    Ortskurve ortskurve = (Ortskurve) methode.invoke(this.ortskurveController, testMesspunkte, testStartpunkt);

    // Es wird berprft, ob der Startpunkt als Ortskurve zurckgegeben worden ist.
    assertEquals(testStartpunkt[0], ortskurve.getMittelpunktOrtskurve().getX(), 0.0);
    assertEquals(testStartpunkt[1], ortskurve.getMittelpunktOrtskurve().getY(), 0.0);
    assertEquals(testStartpunkt[2], ortskurve.getRadiusOrtskurve(), 0.0);
}

From source file:hr.ws4is.websocket.WebSocketOperations.java

private ExtJSResponse executeBean(final Bean<?> bean, final AnnotatedMethod<?> method, final Object[] params) {
    ExtJSResponse response = null;//  w  w w  . j  a v  a 2 s . co  m
    IDestructibleBeanInstance<?> di = null;

    try {
        di = beanManagerUtil.getDestructibleBeanInstance(bean);
        final Object beanInstance = di.getInstance();
        final Method javaMethod = method.getJavaMember();
        if (javaMethod.isAccessible()) {
            javaMethod.setAccessible(true);
        }

        response = (ExtJSResponse) javaMethod.invoke(beanInstance, params);

    } catch (Exception e) {
        response = new ExtJSResponse(e, e.getMessage());
    } finally {
        if (di != null) {
            di.release();
        }
    }

    return response;
}

From source file:com.commsen.liferay.BuildService.java

public void execute() throws MojoExecutionException {

    String webRootFolder = baseDir.getAbsolutePath() + "/" + webappFolderName;
    String srcFolder = baseDir.getAbsolutePath() + "/" + srcFolderName;
    String srcServiceFolder = baseDir.getAbsolutePath() + "/" + serviceApiFolderName;
    String resourcesFolder = baseDir.getAbsolutePath() + "/" + resourcesFolderName;
    String sqlFolder = webRootFolder + "/WEB-INF/sql";

    File inputFile = new File(webRootFolder + "/WEB-INF/service.xml");
    if (!inputFile.exists()) {
        getLog().warn("No service input file (" + inputFile.getAbsolutePath()
                + ") found! Skipping service API generation!");
        return;//from  ww  w.  j a  v  a  2 s. com
    }
    try {
        FileUtils.forceMkdir(new File(sqlFolder));
    } catch (IOException e) {
        getLog().warn(e);
    }
    System.setProperty("external-properties", "com/liferay/portal/tools/dependencies/portal-tools.properties");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
    System.setProperty("service.input.file", inputFile.getAbsolutePath());
    System.setProperty("service.hbm.file", resourcesFolder + "/META-INF/portlet-hbm.xml");
    System.setProperty("service.model.hints.file", resourcesFolder + "/META-INF/portlet-model-hints.xml");
    System.setProperty("service.spring.file", resourcesFolder + "/META-INF/portlet-spring.xml");
    System.setProperty("service.spring.base.file", resourcesFolder + "/META-INF/base-spring.xml");
    System.setProperty("service.spring.dynamic.data.source.file",
            resourcesFolder + "/META-INF/dynamic-data-source-spring.xml");
    System.setProperty("service.spring.hibernate.file", resourcesFolder + "/META-INF/hibernate-spring.xml");
    System.setProperty("service.spring.infrastructure.file",
            resourcesFolder + "/META-INF/infrastructure-spring.xml");
    System.setProperty("service.api.dir", srcServiceFolder);
    System.setProperty("service.impl.dir", srcFolder);
    System.setProperty("service.sql.dir", sqlFolder);
    System.setProperty("service.sql.file", "tables.sql");
    System.setProperty("service.sql.indexes.file", "indexes.sql");
    System.setProperty("service.sql.indexes.properties.file", "indexes.properties");
    System.setProperty("service.sql.sequences.file", "sequences.sql");
    System.setProperty("service.auto.namespace.tables", "true");
    System.setProperty("service.bean.locator.util", "com.liferay.util.bean.PortletBeanLocatorUtil");
    System.setProperty("service.props.util", "com.liferay.util.service.ServiceProps");
    System.setProperty("service.plugin.name", mavenProject.getArtifactId());

    try {
        ClassLoader cl = getClass().getClassLoader();
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(cl, new URL("file://" + resourcesFolder + "/"));
    } catch (Exception e) {
        throw new MojoExecutionException(
                "Failed to modify classloader in order to add resource folder to classpath!", e);
    }

    ServiceBuilder.main(new String[0]);

    if (serviceDependencies != null && !serviceDependencies.isEmpty()) {
        List<Dependency> projectDependecies = mavenProject.getDependencies();
        projectDependecies.addAll(serviceDependencies);
    }
    mavenProject.addCompileSourceRoot(srcServiceFolder);
    File srcServiceProperties = new File(srcFolder, "service.properties");
    File resServiceProperties = new File(resourcesFolder, "service.properties");
    BuildService.deleteQuietly(resServiceProperties);
    try {
        BuildService.moveFile(srcServiceProperties, resServiceProperties);
    } catch (IOException e) {
        getLog().warn(e);
    }
}

From source file:com.searchbox.framework.service.SearchAdapterService.java

private void executeMethod(Object caller, Method method, Object... arguments) {
    try {//from  www.ja v a 2s.  co m
        Long start = System.currentTimeMillis();
        method.setAccessible(true);
        method.invoke(caller, arguments);
        LOGGER.trace("Addapted with {} in {}ms", method.getName(), (System.currentTimeMillis() - start));
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        LOGGER.error("Method name: " + method.getName());
        for (Object object : arguments) {
            LOGGER.error("\t Param: " + object.getClass().getSimpleName() + "\t"
                    + object.toString().replace("\n", " "));
        }
        LOGGER.error(
                "Could not invoke method " + method.getName() + " on: " + caller.getClass().getSimpleName(), e);
    }
}

From source file:com.jaspersoft.jasperserver.util.JasperJdbcContainer.java

/**
 *  This method is a hack, using reflection invokes a private method on the CachedRowSet object to 
 *  extract the parameter payload. /*from ww  w .  java  2 s .  com*/
 * @param crs CachedRowSet 
 * @return
 */
private Object[] getParameters(CachedRowSet crs) {
    Object[] params = null;
    try {
        Method method = crs.getClass().getMethod("getParams", (Class[]) null);
        method.setAccessible(true);
        params = (Object[]) method.invoke(crs, (Object[]) null);
    } catch (NoSuchMethodException e) {
        logger.error(e.getMessage(), e);
        throw new RemoteException("Can't get method name." + e.getMessage());
    } catch (SecurityException e) {
        logger.error(e.getMessage(), e);
        throw new RemoteException("Can't get method name." + e.getMessage());
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage(), e);
        throw new RemoteException("Can't get method name." + e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error(e.getMessage(), e);
        throw new RemoteException("Can't get method name." + e.getMessage());
    } catch (InvocationTargetException e) {
        logger.error(e.getMessage(), e);
        throw new RemoteException("Can't get method name." + e.getMessage());
    }

    return params;

}

From source file:de.thkwalter.koordinatensystem.AchsendimensionierungTest.java

/**
 * Test fr die Methode {@link Achsendimensionierung#wertebereichBestimmen(Vector2D[])}.
 * @throws NoSuchMethodException /*from   ww  w. ja v  a2s  .  c om*/
 * @throws SecurityException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test
public void testWertebereichBestimmen() throws SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    // Die zu testende Methode wird ausgefhrt.
    Method method = Achsendimensionierung.class.getDeclaredMethod("wertebereichBestimmen", Vector2D[].class);
    method.setAccessible(true);
    Wertebereich wertebereich = (Wertebereich) method.invoke(this.achsendimensionierung, (Object) this.punkte);

    // Es wird berprft, ob der korrekte Wertebereich bestimmt worden ist.
    assertEquals(this.punkte[2].getX(), wertebereich.getMaxX(), 0.0);
    assertEquals(this.punkte[0].getX(), wertebereich.getMinX(), 0.0);
    assertEquals(this.punkte[1].getY(), wertebereich.getMaxY(), 0.0);
    assertEquals(this.punkte[3].getY(), wertebereich.getMinY(), 0.0);
}