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:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testGetPhysicalNode() throws Exception {
    PhysicalNodeId physicalNodeId = mock(PhysicalNodeId.class);
    PhysicalNode physicalNode;//w  w  w  .j  a  va  2 s .  c o m

    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("getPhysicalNode", new Class[] { PhysicalNodeId.class });
    method.setAccessible(true);

    physicalNode = (PhysicalNode) method.invoke(physicalResourceLoader, physicalNodeId);

    Assert.assertTrue(physicalNode == null);
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testGetPhysicalPort() throws Exception {
    PhysicalPortId physicalPortId = mock(PhysicalPortId.class);
    PhysicalPort physicalPort;/*  ww w .j a v a 2 s . co m*/

    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("getPhysicalPort", new Class[] { PhysicalPortId.class });
    method.setAccessible(true);

    physicalPort = (PhysicalPort) method.invoke(physicalResourceLoader, physicalPortId);

    Assert.assertTrue(physicalPort == null);
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testGetPhysicalLink() throws Exception {
    PhysicalLinkId physicalLinkId = mock(PhysicalLinkId.class);
    PhysicalLink physicalLink;//from  w  ww.  j a  v a  2s .  c om

    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("getPhysicalLink", new Class[] { PhysicalLinkId.class });
    method.setAccessible(true);

    physicalLink = (PhysicalLink) method.invoke(physicalResourceLoader, physicalLinkId);

    Assert.assertTrue(physicalLink == null);
}

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

public static void setFieldValue(Object target, String name, Class<?> type, Object value) {
    if (target == null || StringUtils.isEmpty(name)
            || (value != null && !type.isAssignableFrom(value.getClass()))) {
        return;/*from ww  w .ja  va  2s  . co m*/
    }
    Class<?> clazz = target.getClass();
    try {
        Method method = clazz
                .getDeclaredMethod("set" + Character.toUpperCase(name.charAt(0)) + name.substring(1), type);
        if (!Modifier.isPublic(method.getModifiers())) {
            method.setAccessible(true);
        }
        method.invoke(target, value);
    } catch (Exception ex) {
        if (LogUtils.isDebug()) {
            logger.debug(ex);
        }
        try {
            Field field = clazz.getDeclaredField(name);
            if (!Modifier.isPublic(field.getModifiers())) {
                field.setAccessible(true);
            }
            field.set(target, value);
        } catch (Exception e) {
            if (LogUtils.isDebug()) {
                logger.debug(e);
            }
        }
    }
}

From source file:net.pms.service.ProcessManager.java

/**
 * Checks if the process is still alive using reflection if possible.
 *
 * @param process the {@link Process} to check.
 * @return {@code true} if the process is still alive, {@code false}
 *         otherwise./*from w w w  . j a v a  2  s  .  c o  m*/
 */
@SuppressFBWarnings("REC_CATCH_EXCEPTION")
public static boolean isProcessIsAlive(@Nullable Process process) {
    if (process == null) {
        return false;
    }
    // XXX replace with Process.isAlive() in Java 8
    try {
        Field field;
        field = process.getClass().getDeclaredField("handle");
        field.setAccessible(true);
        long handle = (long) field.get(process);
        field = process.getClass().getDeclaredField("STILL_ACTIVE");
        field.setAccessible(true);
        int stillActive = (int) field.get(process);
        Method method;
        method = process.getClass().getDeclaredMethod("getExitCodeProcess", long.class);
        method.setAccessible(true);
        int exitCode = (int) method.invoke(process, handle);
        return exitCode == stillActive;
    } catch (Exception e) {
        // Reflection failed, use the backup solution
    }
    try {
        process.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

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

@Test
public void testArgs_invalidInternalCombination()
        throws NoSuchMethodException, ParseException, InvocationTargetException, IllegalAccessException {
    CliParser cliParser = new CliParser();
    Method argsValidation = cliParser.getClass().getDeclaredMethod("areCmdArgsValid", CommandLine.class);
    argsValidation.setAccessible(true);
    CommandLineParser parser = new DefaultParser();

    CommandLine cmdArgs = parser.parse(options, new String[] { "-i", "-w", "1002", "publicApi.xml" });
    Boolean result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertTrue(result);//w w  w .  ja v  a2s . co m

    cmdArgs = parser.parse(options, new String[] { "-i", "-b", "1002", "publicApi.xml" });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);
}

From source file:com.zero.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }//w w  w .ja  va 2s  .  co  m
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.twosigma.beaker.chart.categoryplot.plotitem.CategoryGraphics.java

public void createItemLabels(CategoryPlot plot) {
    if (itemLabelBuilder == null || value == null) {
        this.itemLabels = null;
        return;//w  ww .  ja  v  a2  s . co  m
    }

    int itemCategoriesNumber = value[0].length;
    int itemSeriesNumber = value.length;

    String[][] itemLabels = new String[itemCategoriesNumber][itemSeriesNumber];

    try {
        Class<?> clazz = itemLabelBuilder.getClass();
        Method getMaximumNumberOfParameters = clazz.getMethod("getMaximumNumberOfParameters");
        getMaximumNumberOfParameters.setAccessible(true);
        int numberOfParameters = (int) getMaximumNumberOfParameters.invoke(itemLabelBuilder);

        for (int column = 0; column < itemCategoriesNumber; column++) {
            List<String> categoryNames = plot.getCategoryNames();
            String category = categoryNames != null && categoryNames.size() > column ? categoryNames.get(column)
                    : null;

            for (int row = 0; row < itemSeriesNumber; row++) {

                Number _value = value[row][column];
                String series = seriesNames != null && seriesNames.size() > row ? seriesNames.get(row) : null;

                Method call;
                if (numberOfParameters == 1) {
                    call = clazz.getMethod("call", Object.class);
                    call.setAccessible(true);
                    itemLabels[column][row] = String.valueOf(call.invoke(itemLabelBuilder, _value));
                } else {
                    Object base = getBases() != null
                            ? getBases().get(row) instanceof List ? ((List) getBases().get(row)).get(column)
                                    : getBases().get(row)
                            : getBase();
                    if (numberOfParameters == 2) {
                        call = clazz.getMethod("call", Object.class, Object.class);
                        call.setAccessible(true);
                        itemLabels[column][row] = String.valueOf(call.invoke(itemLabelBuilder, _value, base));
                    } else if (numberOfParameters == 3) {
                        call = clazz.getMethod("call", Object.class, Object.class, Object.class);
                        call.setAccessible(true);
                        itemLabels[column][row] = String
                                .valueOf(call.invoke(itemLabelBuilder, _value, base, series));
                    } else if (numberOfParameters == 4) {
                        call = clazz.getMethod("call", Object.class, Object.class, Object.class, Object.class);
                        call.setAccessible(true);
                        itemLabels[column][row] = String
                                .valueOf(call.invoke(itemLabelBuilder, _value, base, series, category));
                    } else if (numberOfParameters == 5) {
                        call = clazz.getMethod("call", Object.class, Object.class, Object.class, Object.class,
                                Object.class);
                        call.setAccessible(true);
                        itemLabels[column][row] = String
                                .valueOf(call.invoke(itemLabelBuilder, _value, base, series, category, row));
                    } else if (numberOfParameters == 6) {
                        call = clazz.getMethod("call", Object.class, Object.class, Object.class, Object.class,
                                Object.class, Object.class);
                        call.setAccessible(true);
                        itemLabels[column][row] = String.valueOf(
                                call.invoke(itemLabelBuilder, _value, base, series, category, row, column));
                    }
                }

            }
        }
    } catch (Throwable x) {
        throw new RuntimeException("Can not create item labels.", x);
    }

    this.itemLabels = itemLabels;
}

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

@Test
public void testArgs_passwordFile() throws NoSuchMethodException, InvocationTargetException,
        IllegalAccessException, ParseException, URISyntaxException {
    CliParser cliParser = new CliParser();
    Method argsValidation = cliParser.getClass().getDeclaredMethod("areCmdArgsValid", CommandLine.class);
    argsValidation.setAccessible(true);
    CommandLineParser parser = new DefaultParser();

    CommandLine cmdArgs = parser.parse(options,
            new String[] { "--password-file", getClass().getResource("testPasswordFile").toURI().getPath(),
                    getClass().getResource("JUnit-minimalAccepted.xml").toURI().getPath() });
    Boolean result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertTrue(result);/* w  w w. ja v  a  2 s  . c om*/

    cmdArgs = parser.parse(options, new String[] { "--password-file", "invalidPasswordFile",
            getClass().getResource("JUnit-minimalAccepted.xml").toURI().getPath() });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);
}

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

/**
 * Test fr die Methode {@link Achsendimensionierung#sicherheitsabstandHinzufuegen(Wertebereich)}.
 * /*from   w w  w .  j a v  a2s. co  m*/
 * @throws NoSuchMethodException 
 * @throws SecurityException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test
public void testSicherheitsabstandHinzufuegen() throws SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    // Die Testdaten werden erstellt.
    Wertebereich wertebereichPunktemenge = new Wertebereich(10.0, 5.0, 0.0, -5.0);

    // Die zu testende Methode wird ausgefhrt.
    Method method = Achsendimensionierung.class.getDeclaredMethod("sicherheitsabstandHinzufuegen",
            Wertebereich.class);
    method.setAccessible(true);
    Wertebereich wertebereich = (Wertebereich) method.invoke(this.achsendimensionierung,
            wertebereichPunktemenge);

    // Es wird berprft, ob der korrekte Wertebereich bestimmt worden ist.
    assertEquals(11, wertebereich.getMaxX(), 11.0 / 1000);
    assertEquals(-1.0, wertebereich.getMinX(), -1.0 / 1000);
    assertEquals(6.0, wertebereich.getMaxY(), 6.0 / 1000);
    assertEquals(-6.0, wertebereich.getMinY(), -6.0 / 1000);
}