Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethod.

Prototype

@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Usage

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * Invokes the change handler (one of the <code>processChange</code> methods) for the given
 * change object.//from   www . j av a 2 s .  c o m
 * 
 * @param currentModel The current database schema
 * @param params       The parameters used in the creation of new tables. Note that for existing
 *                     tables, the parameters won't be applied
 * @param change       The change object
 */
private void invokeChangeHandler(Database currentModel, CreationParameters params, ModelChange change)
        throws IOException {
    Class curClass = getClass();

    // find the handler for the change
    while ((curClass != null) && !Object.class.equals(curClass)) {
        try {
            Method method = null;

            try {
                method = curClass.getDeclaredMethod("processChange",
                        new Class[] { Database.class, CreationParameters.class, change.getClass() });
            } catch (NoSuchMethodException ex) {
                // we actually expect this one
            }

            if (method != null) {
                method.invoke(this, new Object[] { currentModel, params, change });
                return;
            } else {
                curClass = curClass.getSuperclass();
            }
        } catch (InvocationTargetException ex) {
            if (ex.getTargetException() instanceof IOException) {
                throw (IOException) ex.getTargetException();
            } else {
                throw new DdlUtilsException(ex.getTargetException());
            }
        } catch (Exception ex) {
            throw new DdlUtilsException(ex);
        }
    }
    throw new DdlUtilsException("No handler for change of type " + change.getClass().getName() + " defined");
}

From source file:jsondb.JsonDBTemplate.java

public void join(String sourceID, String sourceCollection, String destID, String destiCollection) {
    Object sourceObj = this.findById(sourceID, sourceCollection);
    Object destObj = this.findById(destID, destiCollection);

    Class sc = sourceObj.getClass();
    Class dc = destObj.getClass();

    String scgettermethod = null;
    String scsettermethod = null;
    String destCollection = null;
    String destField = null;//from   www.j a va  2s  .  co m
    String dcgettermethod = null;
    String dcsettermethod = null;

    Field[] fields = sc.getDeclaredFields();
    for (Field field : fields) {
        DBRef d = field.getDeclaredAnnotation(DBRef.class);
        if (d != null) {
            // destCollection = d.destcollection();
            destField = d.destfieldname();
            // sourcefield = field.getName();
            scgettermethod = "get" + field.getName();
            scsettermethod = "set" + field.getName();
            Method[] methods = sc.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equalsIgnoreCase(scsettermethod)) {
                    scsettermethod = method.getName();
                }
                if (method.getName().equalsIgnoreCase(scgettermethod)) {
                    scgettermethod = method.getName();
                }
            }
        }
    }
    try {
        Method s = sc.getDeclaredMethod(scgettermethod, (Class[]) null);
        String p = (String) s.invoke(sourceObj);

        Field df = dc.getDeclaredField(destField);
        dcgettermethod = "get" + df.getName();
        dcsettermethod = "set" + df.getName();
        Method[] methods = dc.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equalsIgnoreCase(dcsettermethod)) {
                dcsettermethod = method.getName();
            }
            if (method.getName().equalsIgnoreCase(dcgettermethod)) {
                dcgettermethod = method.getName();
            }
        }
        if (p == null) {
            String rs = UUID.randomUUID().toString();
            Method sm = sc.getDeclaredMethod(scsettermethod, rs.getClass());
            sm.invoke(sourceObj, rs);

            Method dm = dc.getDeclaredMethod(dcsettermethod, rs.getClass());
            dm.invoke(destObj, rs);
        } else {
            Method d = dc.getDeclaredMethod(dcsettermethod, p.getClass());
            d.invoke(destObj, p);
        }
        this.upsert(sourceObj);
        this.upsert(destObj);

    } catch (NoSuchMethodException ex) {
        Logger.error("NoSuchMethodExeption");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.error("SecurityException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.error("IllegalAccessException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.error("IllegalArgumentException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.error("InvokationTargetException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.error("Feld not found");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.reloadCollection(destCollection);
    this.reloadCollection(sourceCollection);
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils.NumberObject}
 */// w w  w.j  a  v  a2  s.  co m
@SuppressWarnings("unchecked")
@Test
public void NumberObjectTest() {
    try {
        Class<?> numberObject = ClassLoader.getSystemClassLoader()
                .loadClass(NumberUtils.class.getName() + "$NumberObject");

        Constructor<?> c = numberObject.getDeclaredConstructor(Class.class);
        c.setAccessible(true);

        Method ofType = numberObject.getMethod("of", Class.class);
        ofType.setAccessible(true);

        Method ofN = numberObject.getMethod("of", Number.class);
        ofN.setAccessible(true);

        Method parsable = numberObject.getDeclaredMethod("parsable", Number.class);
        parsable.setAccessible(true);

        Method contains = numberObject.getDeclaredMethod("contains", Number.class);
        contains.setAccessible(true);

        Method valueOf = numberObject.getDeclaredMethod("valueOf", Number.class);
        valueOf.setAccessible(true);

        for (Class<?> type : NUMBERS) {
            Object o = c.newInstance(type);
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            Object numob = ofType.invoke(null, type);
            assertEquals("ofType: " + type.getSimpleName(), o, numob);
            Number n = null;
            if (!type.isPrimitive()) {
                if (ClassUtils.isPrimitiveWrapper(type)) {
                    n = (Number) ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                            .invoke(null, "1");
                } else {
                    n = (Number) type.getField("ONE").get(null);
                }
                if (type.equals(byte.class))
                    assertEquals("ofN: 1: " + type.getSimpleName(), o, ofN.invoke(null, n));
            }
            assertEquals("parsable: -1: " + type.getSimpleName(), true, parsable.invoke(numob, -1));
            assertEquals("parsable: 0: " + type.getSimpleName(), true, parsable.invoke(numob, 0));
            assertEquals("parsable: 1: " + type.getSimpleName(), true, parsable.invoke(numob, 1));

            assertEquals("parsable: null: " + type.getSimpleName(), !type.isPrimitive(),
                    parsable.invoke(numob, (Number) null));

            Object expected = ObjectUtils.isAny(wrapper, Float.class, Double.class, BigDecimal.class,
                    BigInteger.class);
            assertEquals("parsable: Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE));
            assertEquals("parsable: Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.toBigInteger()));
            assertEquals("parsable: Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT));
            assertEquals("parsable: Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.toBigInteger()));
            assertEquals("parsable: -Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate()));
            assertEquals("parsable: -Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate().toBigInteger()));
            assertEquals("parsable: -Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate()));
            assertEquals("parsable: -Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate().toBigInteger()));

            expected = ObjectUtils.isAny(wrapper, Float.class, Double.class);
            assertEquals("parsable: NaN: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NaN));
            assertEquals("parsable: NaN: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NaN));

            if (Byte.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 1234.56f));
            }
            if (Short.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 12345.6f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 123456.789f));
            }
            if (Integer.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123456.789f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456d));
            }
            if (Long.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456f));
            }
            if (Float.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, -Double.MAX_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Double.MAX_VALUE));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, -Double.MAX_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Double.MAX_VALUE));
            }
            if (Double.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));
            }
            if (!ClassUtils.isPrimitiveWrapper(wrapper)) {
                assertEquals("parsable: fraction: " + type.getSimpleName(), BigDecimal.class.equals(type),
                        parsable.invoke(numob, 123.456f));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
            }

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                expected = new BigDecimal("123");
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    n = (Number) valueType.getMethod("valueOf", String.class).invoke(null, "123");
                } else {
                    n = new BigDecimal("123");
                    if (BigInteger.class.equals(valueType))
                        n = ((BigDecimal) n).toBigInteger();
                }
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        expected, valueOf.invoke(numob, n));
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: "
                                + type.getSimpleName(),
                        expected.getClass(), valueOf.invoke(numob, n).getClass());
            }

            n = 123.456f;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Float) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = 1.23456789E-6d;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Double) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2);
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: " + type.getSimpleName(), expected, valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2).negate();
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: negative: " + type.getSimpleName(), expected,
                    valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: negative: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:com.ifnoif.androidtestdemo.customview.VViewPager.java

public void setViewPagerObserver(PagerAdapter pagerAdapter, DataSetObserver observer) {
    Class pagerAdapterClass = PagerAdapter.class;
    try {/* w  w  w  . j av  a2  s. co  m*/
        Method method = pagerAdapterClass.getDeclaredMethod("setViewPagerObserver",
                new Class[] { DataSetObserver.class });
        method.setAccessible(true);
        method.invoke(pagerAdapter, observer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.leelay.galleyviewpager.GalleyViewPager.java

void setViewPagerObserver(PagerAdapter pagerObserver, DataSetObserver observer) {
    Class<? extends PagerAdapter> aClass = pagerObserver.getClass();
    try {/*w w w  . j  a  v  a2s  .c  om*/
        Method setViewPagerObserver = aClass.getDeclaredMethod("setViewPagerObserver", DataSetObserver.class);
        setViewPagerObserver.setAccessible(true);
        setViewPagerObserver.invoke(pagerObserver, observer);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java

/**
 * Parses a method which should be considered in coverage.
 *
 * @param includedClass/*from  ww w.  j  av a2  s.  c  o m*/
 *            the Java class of the method
 * @param includedMethodString
 *            the string representing the included method
 * @param v
 *            a {@link MethodValidator}
 * @param classLoader
 *            the class loader for loading snippet project classes
 */
private void parseIncludedMethod(final Class<?> includedClass, final String includedMethodString,
        final MethodValidator v, final ClassLoader classLoader) {
    Matcher matcher = Snippet.METHOD_STRING_PATTERN.matcher(includedMethodString);

    if (!matcher.matches() || matcher.groupCount() != 2) {
        // invalid method string
        String message = String.format("The included method string must match " + "the required format.\n"
                + "(includedMethodString: [%s])", includedMethodString);
        v.addException(message);
    } else {
        // valid method string
        String includedMethodName = matcher.group(1).trim();
        String[] paramTypeStrings = StringUtils.split(matcher.group(2), ',');
        Class<?>[] paramTypes = new Class<?>[paramTypeStrings.length];
        boolean isConstructor = includedMethodName.equals(includedClass.getSimpleName());
        boolean shouldAdd = true; // only add if there was no problem with
        // the parameters

        // check parameter types
        for (int i = 0; i < paramTypes.length; i++) {
            String parameterTypeString = paramTypeStrings[i].trim();

            if (StringUtils.isBlank(parameterTypeString)) {
                // blank parameter type string
                String message = String.format("The included method string has " + "a blank parameter type.\n"
                        + "(includedMethodString: [%s])\n" + "(index: [%d])", includedMethodString, i);
                v.addException(message);
                shouldAdd = false;
            } else {
                try {
                    paramTypes[i] = ClassUtils.getClass(classLoader, parameterTypeString);
                } catch (ClassNotFoundException e) {
                    // parameter type was not found
                    String format = "The parameter type in " + "the included method string "
                            + "could not have been loaded.\n" + "(includedMethodString: [%s])\n"
                            + "(index: [%d])";
                    String message = String.format(format, includedMethodString, i);
                    v.addException(message);
                    shouldAdd = false;
                }
            }
        }

        if (shouldAdd) {
            // get included method object
            if (isConstructor) {
                try {
                    // only search declared constructors
                    Constructor<?> found = includedClass.getDeclaredConstructor(paramTypes);
                    addIncludedConstructor(found, v);
                } catch (NoSuchMethodException e) {
                    String format = "Included constructor cannot be found "
                            + "(it must be declared in the class)\n" + "(includedClass: [%s])\n"
                            + "(includedMethodString: [%s])";
                    String message = String.format(format, includedClass, includedMethodString);
                    v.addException(message);
                }
            } else {
                try {
                    // only search declared methods
                    Method found = includedClass.getDeclaredMethod(includedMethodName, paramTypes);
                    addIncludedMethod(found, v);
                } catch (NoSuchMethodException e) {
                    String format = "Included method cannot be found " + "(it must be declared in the class)\n"
                            + "(includedClass: [%s])\n" + "(includedMethodString: [%s])";
                    String message = String.format(format, includedClass, includedMethodString);
                    v.addException(message, e);
                }
            }
        }
    }
}

From source file:com.google.flatbuffers.Table.java

@SuppressWarnings("unchecked")
@Override//from  w  w w  .j  a  v  a2s . co  m
public int clone(FlatBufferBuilder builder, Map<String, Object> mutate) throws Exception {
    int root_table = -1;
    Class<?> cls = this.getClass();
    HashMap<String, Object> v = new HashMap<String, Object>();
    try {
        //b0. phan loai method
        List<Method> msAdd = new ArrayList<Method>();
        List<Method> msGet = new ArrayList<Method>();
        HashMap<String, Method> msCreateVector = new HashMap<String, Method>();
        Method[] ms = this.getClass().getDeclaredMethods();
        for (Method m : ms) {
            String sMethodName = m.getName();
            if (m.getParameterTypes().length == 0 && !sMethodName.endsWith("AsByteBuffer"))
                msGet.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("add"))
                msAdd.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("create")
                    && sMethodName.endsWith("Vector"))
                msCreateVector.put(sMethodName, m);
        }
        //b1. lay ds thuoc tinh va gia tri
        for (Method m : msGet) {
            String sMethodName = m.getName();
            if (sMethodName.endsWith("Length")) {
                int ii = sMethodName.lastIndexOf("Length");
                String sMethodName1 = sMethodName.substring(0, ii);
                int iLength = 0;
                try {
                    iLength = (int) m.invoke(this, new Object[] {});
                } catch (Exception e) {
                }
                List<Object> l = new ArrayList<>();
                for (int i = 0; i < iLength; i++) {
                    Method m1 = this.getClass().getDeclaredMethod(sMethodName1,
                            new Class<?>[] { Integer.TYPE });
                    Object oKq = m1.invoke(this, new Object[] { i });
                    l.add(oKq);
                }
                v.put(sMethodName1, l);
            } else {
                Object oKq = m.invoke(this, new Object[] {});
                v.put(sMethodName, oKq);
            }
        }
        //b2. khoi tao gia tri cho builder
        for (Entry<String, Object> e : v.entrySet()) {
            String sKey = e.getKey();
            Object oValue = e.getValue();
            Object oNewValue = mutate != null ? mutate.get(sKey) : null;
            if (oValue instanceof String || oNewValue instanceof String) {
                int keyOffset = builder
                        .createString(oNewValue == null ? oValue.toString() : oNewValue.toString());
                v.put(sKey, keyOffset);
            } else if (oValue instanceof List || oNewValue instanceof List) {
                List<?> oV = (List<?>) (oNewValue == null ? oValue : oNewValue);
                int iLen = ((List<?>) oV).size();
                if (iLen <= 0)
                    v.put(sKey, null);
                else {
                    Object obj = ((List<?>) oV).get(0);
                    if (obj instanceof Table || obj instanceof Struct) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<?>) oV).get(i);
                            int offset = ((IFlatBuffer) obj).clone(builder, null);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else if (obj instanceof String) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<String>) oV).get(i);
                            int offset = builder.createString((CharSequence) obj);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else {
                        int keyOffset = -1;
                        Method m = msCreateVector.get("create" + WordUtils.capitalize(sKey) + "Vector");
                        Class<?> subCls = Class.forName(m.getParameterTypes()[1].getName());
                        Class<?> objType = subCls.getComponentType();
                        String objTypeName = objType.getSimpleName();
                        Method mo = Number.class.getDeclaredMethod(objTypeName + "Value", new Class<?>[] {});
                        Object aObject = Array.newInstance(objType, iLen);
                        for (int i = 0; i < iLen; i++)
                            Array.set(aObject, i, mo.invoke(((List<Number>) oV).get(i), new Object[] {}));
                        keyOffset = (int) m.invoke(null, new Object[] { builder, aObject });
                        if (keyOffset != -1)
                            v.put(sKey, keyOffset);
                    }
                }
            } else if (oValue instanceof Table || oValue instanceof Struct || oNewValue instanceof Table
                    || oNewValue instanceof Struct) {
                int keyOffset = -1;
                if (oNewValue != null)
                    keyOffset = ((IFlatBuffer) oNewValue).clone(builder, mutate);
                else
                    keyOffset = ((IFlatBuffer) oValue).clone(builder, mutate);
                if (keyOffset != -1)
                    v.put(sKey, keyOffset);
            } else {
                if (oNewValue != null)
                    v.put(sKey, oNewValue);
            }
        }
        //b3. gan gia tri cho clone object
        Method m = cls.getDeclaredMethod("start" + cls.getSimpleName(),
                new Class<?>[] { FlatBufferBuilder.class });
        m.invoke(null, new Object[] { builder });
        for (Method mAdd : msAdd) {
            String sFieldName = mAdd.getName().replace("add", "");
            sFieldName = WordUtils.uncapitalize(sFieldName);
            Object oFieldValue = v.get(sFieldName);
            if (oFieldValue != null && !(oFieldValue instanceof Table || oFieldValue instanceof Struct)) {
                mAdd.invoke(null, new Object[] { builder, oFieldValue });
            }
        }
        m = cls.getDeclaredMethod("end" + cls.getSimpleName(), new Class<?>[] { FlatBufferBuilder.class });
        root_table = (int) m.invoke(null, new Object[] { builder });
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return root_table;
}

From source file:org.alfresco.test.PublicBeansBCKTest.java

@Test
public void testSubsystemsBeans() {
    // ensure the abstractPropertyBackedBean abstract bean is still present
    assertTrue(beanDefinitionNames.contains("abstractPropertyBackedBean"));

    // ensure the required setters are still present
    Class<ChildApplicationContextFactory> childAppContextFactoryClass = ChildApplicationContextFactory.class;

    try {/*from  ww w  . j  a va 2 s  . c  o m*/
        Method setRegistryMethod = childAppContextFactoryClass.getMethod("setRegistry",
                new Class[] { PropertyBackedBeanRegistry.class });
        assertNotNull("Expected to find setRegistry method on ChildApplicationContextFactory",
                setRegistryMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setRegistry method on ChildApplicationContextFactory");
    }

    try {
        Method setAutoStartMethod = childAppContextFactoryClass.getMethod("setAutoStart",
                new Class[] { boolean.class });
        assertNotNull("Expected to find setAutoStart method on ChildApplicationContextFactory",
                setAutoStartMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setAutoStart method on ChildApplicationContextFactory");
    }

    try {
        Method setBeanNameMethod = childAppContextFactoryClass.getMethod("setBeanName",
                new Class[] { String.class });
        assertNotNull("Expected to find setBeanName method on ChildApplicationContextFactory",
                setBeanNameMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setBeanName method on ChildApplicationContextFactory");
    }

    try {
        Method setCategoryMethod = childAppContextFactoryClass.getMethod("setCategory",
                new Class[] { String.class });
        assertNotNull("Expected to find setCategory method on ChildApplicationContextFactory",
                setCategoryMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setCategory method on ChildApplicationContextFactory");
    }

    try {
        Method setInstancePathMethod = childAppContextFactoryClass.getMethod("setInstancePath",
                new Class[] { List.class });
        assertNotNull("Expected to find setInstancePath method on ChildApplicationContextFactory",
                setInstancePathMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setInstancePath method on ChildApplicationContextFactory");
    }

    try {
        Method setPropertyDefaultsMethod = childAppContextFactoryClass.getMethod("setPropertyDefaults",
                new Class[] { Properties.class });
        assertNotNull("Expected to find setPropertyDefaults method on ChildApplicationContextFactory",
                setPropertyDefaultsMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setPropertyDefaults method on ChildApplicationContextFactory");
    }

    try {
        Method setEncryptedPropertyDefaultsMethod = childAppContextFactoryClass
                .getMethod("setEncryptedPropertyDefaults", new Class[] { Properties.class });
        assertNotNull("Expected to find setEncryptedPropertyDefaults method on ChildApplicationContextFactory",
                setEncryptedPropertyDefaultsMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setEncryptedPropertyDefaults method on ChildApplicationContextFactory");
    }

    try {
        Method setSaveSetPropertyMethod = childAppContextFactoryClass.getMethod("setSaveSetProperty",
                new Class[] { boolean.class });
        assertNotNull("Expected to find setSaveSetProperty method on ChildApplicationContextFactory",
                setSaveSetPropertyMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setSaveSetProperty method on ChildApplicationContextFactory");
    }

    try {
        Method setCompositePropertyTypesMethod = childAppContextFactoryClass
                .getDeclaredMethod("setCompositePropertyTypes", new Class[] { Map.class });
        assertNotNull("Expected to find setCompositePropertyTypes method on ChildApplicationContextFactory",
                setCompositePropertyTypesMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setCompositePropertyTypes method on ChildApplicationContextFactory");
    }

    try {
        Method setPersisterMethod = childAppContextFactoryClass.getDeclaredMethod("setPersister",
                new Class[] { PropertiesPersister.class });
        assertNotNull("Expected to find setPersister method on ChildApplicationContextFactory",
                setPersisterMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setPersister method on ChildApplicationContextFactory");
    }

    try {
        Method setTypeNameMethod = childAppContextFactoryClass.getDeclaredMethod("setTypeName",
                new Class[] { String.class });
        assertNotNull("Expected to find setTypeName method on ChildApplicationContextFactory",
                setTypeNameMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setTypeName method on ChildApplicationContextFactory");
    }
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo,
        InitializerContext initializerContext) throws Exception {
    HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>();
    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();

    if (xmlNodeInfo != null) {
        if (xmlNodeInfo.isInheritable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);

            propertyTemplate = new AutoPropertyTemplate("parent");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);
        }/*from  w ww.j a  v  a  2s .c  o  m*/

        if (xmlNodeInfo.isScopable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope");
            propertyTemplate.setPrimitive(true);

            Object[] ecs = Scope.class.getEnumConstants();
            String[] enumValues = new String[ecs.length];
            for (int i = 0; i < ecs.length; i++) {
                enumValues[i] = ecs[i].toString();
            }
            propertyTemplate.setEnumValues(enumValues);

            properties.put(propertyTemplate.getName(), propertyTemplate);
        }

        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType());
            if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }

            if (InterceptableDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }
        }

        for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) {
            String propertyName = entry.getKey();
            String value = entry.getValue();

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName);
            propertyTemplate.setDefaultValue(value);
            propertyTemplate.setPrimitive(true);
            propertyTemplate.setFixed(true);
            propertyTemplate.setVisible(false);
            properties.put(propertyName, propertyTemplate);
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            String propertyName = entry.getKey();
            XmlProperty xmlProperty = entry.getValue();
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType());
            Class<?> propertyType = null;
            if (propertyTypeInfo != null) {
                propertyType = propertyTypeInfo.getType();
            }

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty);
            propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
            if (propertyType != null && !propertyType.equals(String.class)) {
                propertyTemplate.setType(propertyType.getName());
            }

            if (xmlProperty.composite()) {
                initCompositeProperty(propertyTemplate, propertyType, initializerContext);
            }
            propertyTemplate.setDeprecated(xmlProperty.deprecated());

            properties.put(propertyName, propertyTemplate);
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getWriteMethod() != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            String propertyName = propertyDescriptor.getName();

            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                continue;
            }

            TypeInfo propertyTypeInfo;
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (Collection.class.isAssignableFrom(propertyType)) {
                propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
                propertyType = propertyTypeInfo.getType();
            } else {
                propertyTypeInfo = new TypeInfo(propertyType, false);
            }

            AutoPropertyTemplate propertyTemplate = null;
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null) {
                if (xmlProperty.unsupported()) {
                    continue;
                }

                propertyTemplate = properties.get(propertyName);
                if (propertyTemplate == null) {
                    propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
                    propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
                }

                if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName)
                        || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) {
                    propertyTemplate.setHighlight(1);
                }

                if (xmlProperty.composite()) {
                    initCompositeProperty(propertyTemplate, propertyType, initializerContext);
                }

                int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes());
                if (clientTypes > 0) {
                    propertyTemplate.setClientTypes(clientTypes);
                }
                propertyTemplate.setDeprecated(xmlProperty.deprecated());
            } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class)
                    || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) {
                propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
            }

            if (propertyTemplate != null) {
                propertyTemplate.setType(propertyDescriptor.getPropertyType().getName());

                if (propertyType.isEnum()) {
                    Object[] ecs = propertyType.getEnumConstants();
                    String[] enumValues = new String[ecs.length];
                    for (int i = 0; i < ecs.length; i++) {
                        enumValues[i] = ecs[i].toString();
                    }
                    propertyTemplate.setEnumValues(enumValues);
                }

                ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
                if (componentReference != null) {
                    ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager,
                            componentReference.value(), "id");
                    propertyTemplate.setReference(referenceTemplate);
                }

                IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class);
                if (ideProperty != null) {
                    propertyTemplate.setVisible(ideProperty.visible());
                    propertyTemplate.setEditor(ideProperty.editor());
                    propertyTemplate.setHighlight(ideProperty.highlight());
                    if (StringUtils.isNotEmpty(ideProperty.enumValues())) {
                        propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;"));
                    }
                }

                ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
                if (clientProperty != null) {
                    propertyTemplate.setDefaultValue(clientProperty.escapeValue());
                }

                properties.put(propertyName, propertyTemplate);
            }
        }
    }
    return properties.values();
}