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:biz.bokhorst.xprivacy.Util.java

public static String getXOption(String name) {
    try {//ww w . j av a2 s  .c o  m
        Class<?> cSystemProperties = Class.forName("android.os.SystemProperties");
        Method spGet = cSystemProperties.getDeclaredMethod("get", String.class);
        String options = (String) spGet.invoke(null, "xprivacy.options");
        Log.w("XPrivacy", "Options=" + options);
        if (options != null)
            for (String option : options.split(",")) {
                String[] nv = option.split("=");
                if (nv[0].equals(name))
                    if (nv.length > 1)
                        return nv[1];
                    else
                        return "true";
            }
    } catch (Throwable ex) {
        Log.e("XPrivacy", ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
    return null;
}

From source file:com.cenrise.test.azkaban.Utils.java

public static Object invokeStaticMethod(final ClassLoader loader, final String className,
        final String methodName, final Object... args) throws ClassNotFoundException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    final Class<?> clazz = loader.loadClass(className);

    final Class<?>[] argTypes = new Class[args.length];
    for (int i = 0; i < args.length; ++i) {
        // argTypes[i] = args[i].getClass();
        argTypes[i] = args[i].getClass();
    }//www  .ja  v  a2 s  . c  o m

    final Method method = clazz.getDeclaredMethod(methodName, argTypes);
    return method.invoke(null, args);
}

From source file:ch.aonyx.broker.ib.api.util.AnnotationUtils.java

/**
 * Get a single {@link Annotation} of <code>annotationType</code> from the supplied {@link Method}, traversing its
 * super methods if no annotation can be found on the given method itself.
 * <p>//from  w w  w.j  a v  a 2s .c  om
 * Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * 
 * @param method
 *            the method to look for annotations on
 * @param annotationType
 *            the annotation class to look for
 * @return the annotation found, or <code>null</code> if none found
 */
public static <A extends Annotation> A findAnnotation(final Method method, final Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> cl = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
    }
    while (annotation == null) {
        cl = cl.getSuperclass();
        if ((cl == null) || (cl == Object.class)) {
            break;
        }
        try {
            final Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
            if (annotation == null) {
                annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
            }
        } catch (final NoSuchMethodException ex) {
            // We're done...
        }
    }
    return annotation;
}

From source file:com.yunshan.cloudstack.vmware.util.VmwareHelper.java

public static String getExceptionMessage(Throwable e, boolean printStack) {
    // TODO: in vim 5.1, exceptions do not have a base exception class,
    // MethodFault becomes a FaultInfo that we can only get
    // from individual exception through getFaultInfo, so we have to use
    // reflection here to get MethodFault information.
    try {/*from   w w w. j  ava  2 s  .  c  om*/
        Class<? extends Throwable> cls = e.getClass();
        Method mth = cls.getDeclaredMethod("getFaultInfo", (Class<?>) null);
        if (mth != null) {
            Object fault = mth.invoke(e, (Object[]) null);
            if (fault instanceof MethodFault) {
                final StringWriter writer = new StringWriter();
                writer.append("Exception: " + fault.getClass().getName() + "\n");
                writer.append("message: " + ((MethodFault) fault).getFaultMessage() + "\n");

                if (printStack) {
                    writer.append("stack: ");
                    e.printStackTrace(new PrintWriter(writer));
                }
                return writer.toString();
            }
        }
    } catch (Exception ex) {

    }

    return ExceptionUtil.toString(e, printStack);
}

From source file:Mopex.java

/**
 * Returns a Method that has the signature specified by the calling
 * parameters./*from w ww.  j a  v  a2  s  .  c  o m*/
 * 
 * @return Method
 * @param cls
 *            java.lang.Class
 * @param name
 *            String
 * @param paramTypes
 *            java.lang.Class[]
 */
//start extract getSupportedMethod
public static Method getSupportedMethod(Class cls, String name, Class[] paramTypes)
        throws NoSuchMethodException {
    if (cls == null) {
        throw new NoSuchMethodException();
    }
    try {
        return cls.getDeclaredMethod(name, paramTypes);
    } catch (NoSuchMethodException ex) {
        return getSupportedMethod(cls.getSuperclass(), name, paramTypes);
    }
}

From source file:net.sf.jabref.openoffice.OpenOfficePanel.java

private static void addURL(List<URL> jarList) throws IOException {
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;
    try {//from w ww  . j a  va2s . c o m
        Method method = sysclass.getDeclaredMethod("addURL", CLASS_PARAMETERS);
        method.setAccessible(true);
        for (URL anU : jarList) {
            method.invoke(sysloader, anU);
        }
    } catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        LOGGER.error("Could not add URL to system classloader", e);
        throw new IOException("Error, could not add URL to system classloader");

    }
}

From source file:Main.java

public static Drawable showUninstallAPKIcon(Context context, String apkPath) {
    String PATH_PackageParser = "android.content.pm.PackageParser";
    String PATH_AssetManager = "android.content.res.AssetManager";
    try {/*  w w w  .j  a  v a 2s  . c  om*/
        Class<?> pkgParserCls = Class.forName(PATH_PackageParser);
        Class<?>[] typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs);
        Object[] valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        Object pkgParser = pkgParserCt.newInstance(valueArgs);
        DisplayMetrics metrics = new DisplayMetrics();
        metrics.setToDefaults();
        typeArgs = new Class[4];
        typeArgs[0] = File.class;
        typeArgs[1] = String.class;
        typeArgs[2] = DisplayMetrics.class;
        typeArgs[3] = Integer.TYPE;
        Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs);
        valueArgs = new Object[4];
        valueArgs[0] = new File(apkPath);
        valueArgs[1] = apkPath;
        valueArgs[2] = metrics;
        valueArgs[3] = 0;
        Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);
        Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
        ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
        Class<?> assetMagCls = Class.forName(PATH_AssetManager);
        Constructor<?> assetMagCt = assetMagCls.getConstructor((Class[]) null);
        Object assetMag = assetMagCt.newInstance((Object[]) null);
        typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs);
        valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
        Resources res = context.getResources();
        typeArgs = new Class[3];
        typeArgs[0] = assetMag.getClass();
        typeArgs[1] = res.getDisplayMetrics().getClass();
        typeArgs[2] = res.getConfiguration().getClass();
        Constructor<?> resCt = Resources.class.getConstructor(typeArgs);
        valueArgs = new Object[3];
        valueArgs[0] = assetMag;
        valueArgs[1] = res.getDisplayMetrics();
        valueArgs[2] = res.getConfiguration();
        res = (Resources) resCt.newInstance(valueArgs);
        if (info.icon != 0) {
            Drawable icon = res.getDrawable(info.icon);
            return icon;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java

public static List<SuggestFieldInfo> getSuggestFieldInfoList(final SuggestUpdateConfig config) {
    final List<SuggestFieldInfo> list = new ArrayList<SuggestFieldInfo>();

    for (final SuggestUpdateConfig.FieldConfig fieldConfig : config.getFieldConfigList()) {
        try {//from  www  .ja va  2s  . c  o m
            final List<String> fieldNameList = Arrays.asList(fieldConfig.getTargetFields());
            final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = fieldConfig.getTokenizerConfig();

            //create tokenizerFactory
            TokenizerFactory tokenizerFactory = null;
            if (tokenizerConfig != null) {
                final Class<?> cls = Class.forName(tokenizerConfig.getClassName());
                final Constructor<?> constructor = cls.getConstructor(Map.class);
                tokenizerFactory = (TokenizerFactory) constructor.newInstance(tokenizerConfig.getArgs());
                try {
                    final Class[] params = new Class[] { ResourceLoader.class };
                    final Method inform = cls.getDeclaredMethod("inform", params);
                    final Object[] args = new Object[] { new FilesystemResourceLoader() };
                    inform.invoke(tokenizerFactory, args);
                } catch (final NoSuchMethodException e) {
                    //ignore
                } catch (final Exception e) {
                    logger.warn("Failed to execute inform of tokenizer.", e);
                }
            }

            //create converter
            final SuggestIntegrateConverter suggestIntegrateConverter = new SuggestIntegrateConverter();
            for (final SuggestUpdateConfig.ConverterConfig converterConfig : fieldConfig
                    .getConverterConfigList()) {
                final SuggestReadingConverter suggestReadingConverter = SuggestUtil
                        .createConverter(converterConfig.getClassName(), converterConfig.getProperties());
                suggestIntegrateConverter.addConverter(suggestReadingConverter);
            }
            if (tokenizerFactory != null) {
                suggestIntegrateConverter.setTokenizerFactory(tokenizerFactory);
            }
            suggestIntegrateConverter.start();

            //create normalizer
            final SuggestIntegrateNormalizer suggestIntegrateNormalizer = new SuggestIntegrateNormalizer();
            for (final SuggestUpdateConfig.NormalizerConfig normalizerConfig : fieldConfig
                    .getNormalizerConfigList()) {
                final SuggestNormalizer suggestNormalizer = SuggestUtil
                        .createNormalizer(normalizerConfig.getClassName(), normalizerConfig.getProperties());
                suggestIntegrateNormalizer.addNormalizer(suggestNormalizer);
            }
            suggestIntegrateNormalizer.start();

            final SuggestFieldInfo suggestFieldInfo = new SuggestFieldInfo(fieldNameList, tokenizerFactory,
                    suggestIntegrateConverter, suggestIntegrateNormalizer);
            list.add(suggestFieldInfo);
        } catch (final Exception e) {
            throw new FessSuggestException(
                    "Failed to create Tokenizer." + fieldConfig.getTokenizerConfig().getClassName(), e);
        }
    }
    return list;
}

From source file:com.aliyun.openservices.odps.console.utils.CommandParserUtils.java

private static AbstractCommand reflectCommandObject(String commandName, Class<?>[] argTypes, Object... args)
        throws ODPSConsoleException {

    Class<?> commandClass = null;
    try {/*  www  .  j a  va2s.c o m*/

        if (classLoader == null) {
            loadPlugins();
        }

        commandClass = Class.forName(commandName, false, classLoader);
        Method parseMethod = commandClass.getDeclaredMethod("parse", argTypes);

        Object commandObject = parseMethod.invoke(null, args);

        if (commandObject != null) {
            return (AbstractCommand) commandObject;
        } else {
            return null;
        }
    } catch (ClassNotFoundException e) {
        // Console??AssertionError
        throw new AssertionError("Cannot find the command:" + commandName);
    } catch (SecurityException e) {
        throw new AssertionError("Cannot find the parse method on the command: " + commandName);
    } catch (NoSuchMethodException e) {
        //FOR there's two kind of command,not throw exception
        return null;
    } catch (IllegalArgumentException e) {
        throw new AssertionError("Failed to invoke the parse method on the command:" + commandName);
    } catch (IllegalAccessException e) {
        throw new AssertionError("Failed to invoke the parse method on the command:" + commandName);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof ODPSConsoleException) {
            String msg = e.getCause().getMessage();
            if (!StringUtils.isNullOrEmpty(msg) && msg.contains(ODPSConsoleConstants.BAD_COMMAND)
                    && commandClass != null) {
                String output = getCommandUsageString(commandClass);
                if (output != null) {
                    throw new ODPSConsoleException(e.getCause().getMessage() + "\n" + output);
                }
            }
            throw (ODPSConsoleException) e.getCause();
        } else {
            throw new ODPSConsoleException(e.getCause());
        }
    }
}

From source file:Main.java

public static void setProperties(Object object, Map<String, ? extends Object> properties,
        boolean includeSuperClasses) {
    if (object == null || properties == null) {
        return;//from w w w  .j a v a  2  s .c om
    }

    Class<?> objectClass = object.getClass();

    for (Map.Entry<String, ? extends Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (key != null && key.length() > 0) {
            String setterName = "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);
            Method setter = null;

            // Try to use the exact setter
            if (value != null) {
                try {
                    if (includeSuperClasses) {
                        setter = objectClass.getMethod(setterName, value.getClass());
                    } else {
                        setter = objectClass.getDeclaredMethod(setterName, value.getClass());
                    }
                } catch (Exception ex) {
                }
            }

            // Find a more generic setter
            if (setter == null) {
                Method[] methods = includeSuperClasses ? objectClass.getMethods()
                        : objectClass.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.getName().equals(setterName)) {
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        if (parameterTypes.length == 1 && isAssignableFrom(parameterTypes[0], value)) {
                            setter = method;
                            break;
                        }
                    }
                }
            }

            // Invoke
            if (setter != null) {
                try {
                    setter.invoke(object, value);
                } catch (Exception e) {
                }
            }
        }
    }
}