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:com.haulmont.cuba.core.config.ConfigUtil.java

/**
 * Get the default value of a configuration interface method. If a
 * {@link Default} annotation is present then that string is converted
 * to the appropriate type using the {@link TypeFactory} class.
 * Otherwise, for the type Foo, this searches for a FooDefault
 * annotation. If such an annotation is present then its value is
 * returned./* w w w  .  j a  v a2s.  c o  m*/
 *
 * @param configInterface The configuration interface.
 * @param method          The method.
 * @return The default value, or null.
 */
public static String getDefaultValue(Class<?> configInterface, Method method) {
    // TODO: returnType.cast()?
    try {
        Default defaultValue = method.getAnnotation(Default.class);
        if (defaultValue != null) {
            return defaultValue.value();
        } else {
            Class<?> type = method.getReturnType();
            if (EnumClass.class.isAssignableFrom(type)) {
                @SuppressWarnings("unchecked")
                Class<EnumClass> enumeration = (Class<EnumClass>) type;
                EnumStore mode = getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    Class<?> idType = getEnumIdType(enumeration);
                    String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(idType));
                    Object value = getAnnotationValue(method, name);
                    if (value != null) {
                        Method fromId = enumeration.getDeclaredMethod("fromId", idType);
                        TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                        return stringConverter.stringify(fromId.invoke(null, value));
                    }
                    return NO_DEFAULT;
                }
            }
            String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(type));
            Object value = getAnnotationValue(method, name);
            if (value != null) {
                TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                return stringConverter.stringify(value);
            }
        }
        return NO_DEFAULT;
    } catch (Exception ex) {
        throw new RuntimeException("Default value error", ex);
    }
}

From source file:fr.cnes.sitools.extensions.astro.application.uws.jobmanager.AbstractJobTask.java

/**
 * Returns the get Capabilities of the Runnable job.
 *
 * @param className runnable class//from   w  w  w.  j  ava 2  s.c om
 * @return the get Capabilities of the Runnable job
 */
public static final Job getCapabilities(final String className) {
    Job job = null;
    try {
        final Class c = Class.forName(className);
        final Object obj = c.newInstance();
        final Method m = c.getDeclaredMethod("getCapabilities", null);
        job = (Job) m.invoke(obj, null);
    } catch (ClassNotFoundException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchMethodException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Engine.getLogger(AbstractJobTask.class.getName()).log(Level.SEVERE, null, ex);
    }
    return job;
}

From source file:org.apache.flume.sink.hbase.TestAsyncHBaseSink.java

@BeforeClass
public static void setUp() throws Exception {

    /*//from ww w  .j av a2  s.co m
     * Borrowed from HCatalog ManyMiniCluster.java
     * https://svn.apache.org/repos/asf/incubator/hcatalog/trunk/
     * storage-handlers/hbase/src/test/org/apache/hcatalog/
     * hbase/ManyMiniCluster.java
     *
     */
    String hbaseDir = new File(workDir, "hbase").getAbsolutePath();
    String hbaseRoot = "file://" + hbaseDir;
    Configuration hbaseConf = HBaseConfiguration.create();

    hbaseConf.set(HConstants.HBASE_DIR, hbaseRoot);
    hbaseConf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, 2181);
    hbaseConf.set(HConstants.ZOOKEEPER_QUORUM, "0.0.0.0");
    hbaseConf.setInt("hbase.master.info.port", -1);
    hbaseConf.setInt("hbase.zookeeper.property.maxClientCnxns", 500);
    String zookeeperDir = new File(workDir, "zk").getAbsolutePath();
    int zookeeperPort = 2181;
    zookeeperCluster = new MiniZooKeeperCluster();
    Method m;
    Class<?> zkParam[] = { Integer.TYPE };
    try {
        m = MiniZooKeeperCluster.class.getDeclaredMethod("setDefaultClientPort", zkParam);
    } catch (NoSuchMethodException e) {
        m = MiniZooKeeperCluster.class.getDeclaredMethod("setClientPort", zkParam);
    }

    m.invoke(zookeeperCluster, new Object[] { new Integer(zookeeperPort) });
    zookeeperCluster.startup(new File(zookeeperDir));
    hbaseCluster = new MiniHBaseCluster(hbaseConf, 1);
    HMaster master = hbaseCluster.getMaster();
    Object serverName = master.getServerName();
    String hostAndPort;
    if (serverName instanceof String) {
        System.out.println("Server name is string, using HServerAddress.");
        m = HMaster.class.getDeclaredMethod("getMasterAddress", new Class<?>[] {});
        Class<?> clazz = Class.forName("org.apache.hadoop.hbase.HServerAddress");
        /*
         * Call method to get server address
         */
        Object serverAddr = clazz.cast(m.invoke(master, new Object[] {}));
        //returns the address as hostname:port
        hostAndPort = serverAddr.toString();
    } else {
        System.out.println("ServerName is org.apache.hadoop.hbase.ServerName," + "using getHostAndPort()");
        Class<?> clazz = Class.forName("org.apache.hadoop.hbase.ServerName");
        m = clazz.getDeclaredMethod("getHostAndPort", new Class<?>[] {});
        hostAndPort = m.invoke(serverName, new Object[] {}).toString();
    }

    hbaseConf.set("hbase.master", hostAndPort);
    testUtility = new HBaseTestingUtility(hbaseConf);
    testUtility.setZkCluster(zookeeperCluster);
    hbaseCluster.startMaster();
    Map<String, String> ctxMap = new HashMap<String, String>();
    ctxMap.put("table", tableName);
    ctxMap.put("columnFamily", columnFamily);
    ctxMap.put("serializer", "org.apache.flume.sink.hbase.SimpleAsyncHbaseEventSerializer");
    ctxMap.put("serializer.payloadColumn", plCol);
    ctxMap.put("serializer.incrementColumn", inColumn);
    ctx.putAll(ctxMap);
}

From source file:gov.llnl.lc.smt.command.file.SmtFile.java

private static String getFileInfo(String fileName, boolean includeTimeStamps) {
    String fn = convertSpecialFileName(fileName);

    //parameter types for all read file (just a filename)
    Class[] partypes = new Class[] { String.class };

    //Arguments to be passed into method
    Object[] arglist = new String[] { fn };

    // sort the various types based on the the priority (or probability)
    TreeSet<SmtProperty> ft = SmtProperty.sortPropertySet(SmtProperty.SMT_FILE_TYPES);

    for (SmtProperty s : ft) {
        /* TODO move this to a different enum, this is a hack */
        String className = s.getPropertyName();
        String methodRead = s.getName();
        String methodInfo = s.getShortName();
        String methodListTS = s.getArgName();

        // attempt to open this file, using this class
        Class<?> smtClass = null;
        try {/*from  w  w  w  .  ja  v  a 2 s.c  o m*/
            String timeString = "";
            smtClass = Class.forName(className);
            Method r = smtClass.getDeclaredMethod(methodRead, partypes);
            Object o = r.invoke(null, arglist);

            // previous should throw an exception if not the correct type, but...
            // final sanity check

            String type = o.getClass().getCanonicalName();
            if (!className.equals(type)) {
                logger.info("File NOT: " + className + " (" + type + ")");
                continue;
                //            
                //            return "Could not get File Info";
                //            return "Could not get File Info";
            }

            // if I am here, then it worked, so I know the type of file it is
            // now invoke the other method to return the info, or the timelist string
            Method i = smtClass.getDeclaredMethod(methodInfo, (java.lang.Class<?>[]) null);
            Object str = i.invoke(o, (java.lang.Object[]) null);

            // conditionally get the timelist too
            if (includeTimeStamps) {
                Method t = smtClass.getDeclaredMethod(methodListTS, (java.lang.Class<?>[]) null);
                Object strT = t.invoke(o, (java.lang.Object[]) null);
                timeString = "\ntimestamp list:\n" + strT.toString();
            }

            // I know this is a string
            return str.toString() + timeString;
        } catch (Exception e) {
            logger.info("File is NOT: " + className);
        }
    }
    return "Could not obtain File Info";
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Method} with a certain name and parameter types declared in the given class or any subclass
 * (except {@link Object}).//w w  w. ja v a  2 s .  c  o  m
 * <p/>
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} the parameter types are ignored
 * for signature comparison.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared methods are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the method and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several methods were found.
 * 
 * @param type the class
 * @param methodName the name of the method to find
 * @param clazzes the full-qualified class names of the parameters
 * @return the accessible method resolved
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
public static Method findMethod(final Class<?> type, String methodName, Class<?>... clazzes)
        throws ClassNotFoundException {
    Method method = null;

    // If all parameter types are known, find the method that exactly matches the signature
    if (clazzes != null && !ArrayUtils.contains(clazzes, null)) {
        for (Class<?> clazz = type; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = type.getDeclaredMethod(methodName, clazzes);
                break;
            } catch (NoSuchMethodException e) {
                // Ignore
            }
        }
    }

    // If no method was found, find all possible candidates
    if (method == null) {
        List<Method> candidates = new ArrayList<>();
        for (Class<?> clazz = type; clazz != null; clazz = clazz.getSuperclass()) {
            for (Method declaredMethod : clazz.getDeclaredMethods()) {
                if (declaredMethod.getName().equals(methodName) && (clazzes == null
                        || ClassUtils.isAssignable(clazzes, declaredMethod.getParameterTypes()))) {

                    // Check if there is already a overridden method with the same signature
                    for (Method candidate : candidates) {
                        if (candidate.getName().equals(declaredMethod.getName())) {
                            /**
                             * If there is at least one parameters in the method of the super type, which is a
                             * sub type of the corresponding parameter of the sub type, remove the method declared
                             * in the sub type.
                             */
                            if (!Arrays.equals(declaredMethod.getParameterTypes(),
                                    candidate.getParameterTypes())
                                    && ClassUtils.isAssignable(declaredMethod.getParameterTypes(),
                                            candidate.getParameterTypes())) {
                                candidates.remove(candidate);
                            } else {
                                declaredMethod = null;
                            }
                            break;
                        }
                    }

                    // If the method has a different signature matching the given types, add it to the candidates
                    if (declaredMethod != null) {
                        candidates.add(declaredMethod);
                    }
                }
            }
        }

        if (candidates.size() != 1) {
            throw new JCloudScaleException(
                    String.format("Cannot find distinct method '%s.%s()' with parameter types %s", type,
                            methodName, Arrays.toString(clazzes)));
        }
        method = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(method);
    if (method != null && !method.isAccessible())
        method.setAccessible(true);

    return method;

}

From source file:org.cloudfoundry.identity.uaa.coverage.CoverageController.java

@RequestMapping(value = "flush", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveGlobalProjectData() throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException {
    String className = "net.sourceforge.cobertura.coveragedata.ProjectData";
    String methodName = "saveGlobalProjectData";
    Class saveClass = Class.forName(className);
    java.lang.reflect.Method saveMethod = saveClass.getDeclaredMethod(methodName, new Class[0]);
    saveMethod.invoke(null, new Object[0]);
    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:com.krawler.runtime.utils.URLClassLoaderUtil.java

public void addJarURL(URL u) throws Exception {
    try {//from w ww  .j  a v  a  2s. c  o m

        URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL urls[] = sysLoader.getURLs();
        for (int i = 0; i < urls.length; i++) {
            if (StringUtils.equalsIgnoreCase(urls[i].toString(), u.toString())) {
                if (log.isDebugEnabled()) {
                    log.debug("URL " + u + " is already in the CLASSPATH");
                }
                return;
            }
        }
        Class sysclass = URLClassLoader.class;
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error, could not add URL to system classloader" + e.getMessage());
    }

}

From source file:org.apache.hadoop.metrics2.lib.DefaultMetricsSystemHelper.java

public DefaultMetricsSystemHelper() {
    Method m;//from  ww w.  j  a v  a 2s  . com
    try {
        Class<? extends DefaultMetricsSystem> clazz = DefaultMetricsSystem.INSTANCE.getClass();
        m = clazz.getDeclaredMethod("removeObjectName", String.class);
        m.setAccessible(true);
    } catch (NoSuchMethodException e) {
        m = null;
    }
    removeObjectMethod = m;
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Return a static method of a class./*from w ww. j  a v  a  2 s . c  o  m*/
 * @param methodName the static method name
 * @param clazz   the class which defines the method
 * @param args the parameter types to the method
 * @return the static method, or <code>null</code> if no static method was found
 * @throws IllegalArgumentException if the method name is blank or the clazz is null
 */
public static Method getStaticMethod(Class clazz, String methodName, Class[] args) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    try {
        Method method = clazz.getDeclaredMethod(methodName, args);
        if ((method.getModifiers() & Modifier.STATIC) != 0) {
            return method;
        }
    } catch (NoSuchMethodException ex) {
    }
    return null;
}

From source file:org.openmrs.module.metadatasharing.reflection.ReplaceMethodInovker.java

public Method getMethod(Class<?> type, String name, Class<?>... parameterTypes) {
    try {//w  w  w.j  a  v a  2  s . c om
        Method result = type.getDeclaredMethod(name, parameterTypes);
        result.setAccessible(true);
        return result;
    } catch (NoSuchMethodException e) {
        return null;
    }
}