Example usage for java.lang Class getMethod

List of usage examples for java.lang Class getMethod

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:de.alpharogroup.lang.ObjectExtensions.java

/**
 * Try to clone the given object.//w w  w .  j ava  2  s  .c o  m
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:org.agiso.core.lang.util.ClassUtils.java

/**
 * Wyszukuje dla wskazanej klasy publiczn metod o okrelonej sygnaturze. Jeli
 * metoda nie zostanie naleziona zwraca {@code null}.
 * <p>W przypadku gdy nie jest okrelona tablica parametrw wywoania, zwraca metod
 * tylko gdy wynik wyszukiwania jest unikatowy, tj. istnieje tylko jedna publiczna
 * metoda o wskazanej nazwie./*from   w w w .  j  a v a 2s  . c om*/
 * 
 * <p>Based on:
 * org.springframework.util.ClassUtils.getMethodIfAvailable(Class<?>, String, Class<?>...)
 * 
 * @param clazz Klasa do sprawdzenia
 * @param methodName Nazwa wyszukiwanej metody
 * @param paramTypes Tablica typw parametrw wywoania metody
 *     (moe by {@code null} w celu wyszukania dowolnej metody o wskazanej nazwie)
 * @return Znaleziona metoda lub @{code null} gdy nie istnieje lub nie jest unikatowa
 * @see Class#getMethod
 */
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    if (clazz == null) {
        throw new NullPointerException("Klasa musi by okrelona");
    }
    if (methodName == null) {
        throw new NullPointerException("Nazwa metody musi by okrelona");
    }

    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}

From source file:com.aurel.track.admin.customize.scripting.GroovyScriptExecuter.java

/**
 * Helper method for parameter classes. The "parameter" script are probably
 * changed according to the customer needs while the logic scripts are
 * relative stable (probably not changed by the customer) If the parameter
 * script is changed (and automatically recompiled) the original "parameter"
 * class file seems to remain in the Groovy classpath. In the local
 * GroovyScriptLoader cache (availableClasses map) the actual version is
 * stored That's why in the logic scripts the parameter script's
 * fields/methods shouldn't be accessed directly (it contains the old
 * version of the class from the Groovy classpath) but from the
 * GroovyScriptLoader cache through reflection.
 *
 * @param handlerClass/*from   w ww.  jav  a2 s  .  c o  m*/
 * @param methodName
 * @return
 */
public static Object getParameterInstanceGroovyHandler(String handlerClass, String methodName) {
    if (GroovyScriptLoader.getInstance().doesGroovyClassExist(handlerClass)) {
        try {
            Class groovyClass = GroovyScriptLoader.getInstance().getGroovyClass(handlerClass);
            Object object = null;
            Method getInstance = groovyClass.getMethod("getInstance", new Class[] {});
            if (getInstance != null) {
                // if getInstance() exists get the already initialized
                // "parameter" object (instance of "parameter" class)
                object = getInstance.invoke(groovyClass, new Object[] {});
            } else {
                // no getInstance(): always create and initialize a new
                // "parameter" object (instance of "parameter" class)
                object = groovyClass.newInstance();
            }
            // method name (probably a getter method)
            Method method = groovyClass.getMethod(methodName, new Class[] {});
            return method.invoke(object, (Object[]) new Class[] {});
        } catch (Exception e) {
            LOGGER.warn("Problem calling Groovy EventHandler: " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } else {
        LOGGER.debug("The Groovy class " + handlerClass + " was not found");
    }
    return null;
}

From source file:org.agiso.core.lang.util.ClassUtils.java

/**
 * Wyszukuje dla wskazanej klasy publiczn metod o okrelonej sygnaturze. Jeli
 * metoda nie zostanie naleziona wyrzuca wyjtek {@code IllegalStateException}.
 * <p>W przypadku gdy nie jest okrelona tablica parametrw wywoania, zwraca metod
 * tylko gdy wynik wyszukiwania jest unikatowy, tj. istnieje tylko jedna publiczna
 * metoda o wskazanej nazwie./*from w  ww  .j a va  2  s.c o  m*/
 * 
 * <p>Based on:
 * org.springframework.util.ClassUtils.getMethod(Class<?>, String, Class<?>...)
 * 
 * @param clazz Klasa do sprawdzenia
 * @param methodName Nazwa wyszukiwanej metody
 * @param paramTypes Tablica typw parametrw wywoania metody
 *     (moe by {@code null} w celu wyszukania dowolnej metody o wskazanej nazwie)
 * @return Znaleziona metoda (niegdy {@code null})
 * @throws IllegalStateException jeli nie znaleziono metody lub nie jest unikatowa
 * @see Class#getMethod
 */
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    if (clazz == null) {
        throw new NullPointerException("Klasa musi by okrelona");
    }
    if (methodName == null) {
        throw new NullPointerException("Nazwa metody musi by okrelona");
    }

    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException("Expected method not found: " + ex);
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        } else if (candidates.isEmpty()) {
            throw new IllegalStateException("Expected method not found: " + clazz + "." + methodName);
        } else {
            throw new IllegalStateException("No unique method found: " + clazz + "." + methodName);
        }
    }
}

From source file:com.github.michalbednarski.intentslab.Utils.java

@TargetApi(13) // Function handles all supported api levels
public static InputStream dumpSystemService(Context context, String serviceName, final String[] arguments)
        throws Exception {
    // Check if we have permission to invoke dump from our process
    final boolean canDumpLocally = context.getPackageManager().checkPermission(android.Manifest.permission.DUMP,
            context.getPackageName()) == PackageManager.PERMISSION_GRANTED;

    // On versions without createPipe() just execute dumpsys
    if (android.os.Build.VERSION.SDK_INT < 9) {
        if (!canDumpLocally) {
            throw new Exception("Dumping is not supported on this system version");
        }/*  ww w  .ja va  2s .co  m*/
        String[] progArray = new String[arguments != null ? 2 + arguments.length : 2];
        progArray[0] = "dumpsys";
        progArray[1] = serviceName;
        if (arguments != null) {
            System.arraycopy(arguments, 0, progArray, 2, arguments.length);
        }
        return Runtime.getRuntime().exec(progArray).getInputStream();
    }

    // Get service
    final Class<?> serviceManager = Class.forName("android.os.ServiceManager");
    final IBinder service = (IBinder) serviceManager.getMethod("getService", String.class).invoke(null,
            serviceName);

    // Check permissions and get remote interface if needed
    IRemoteInterface remoteInterface = null;
    if (!canDumpLocally) {
        remoteInterface = RunAsManager.getRemoteInterfaceForSystemDebuggingCommands();
        if (remoteInterface == null) {
            throw new SecurityException("Process has no permission to dump services");
        }
    }

    // Create pipe, write(pipe[0]) -> read(pipe[1])
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final ParcelFileDescriptor readablePipe = pipe[0];
    final ParcelFileDescriptor writablePipe = pipe[1];

    try {
        // Execute dump
        if (canDumpLocally) {
            if (android.os.Build.VERSION.SDK_INT >= 13) {
                service.dumpAsync(writablePipe.getFileDescriptor(), arguments);
                writablePipe.close();
            } else {
                (new Thread() {
                    @Override
                    public void run() {
                        try {
                            service.dump(writablePipe.getFileDescriptor(), arguments);
                            writablePipe.close();
                        } catch (Exception e) {
                            // TODO: can we handle this?
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else {
            remoteInterface.dumpServiceAsync(service, writablePipe, arguments);
            writablePipe.close();
        }
        // If anything went wrong, close pipe and rethrow
    } catch (Throwable e) {
        readablePipe.close();
        writablePipe.close();
        throwUnchecked(e);
        throw new Error(); // Unreachable
    }

    // Return stream that will ensure closing fd
    return new FileInputStream(readablePipe.getFileDescriptor()) {
        @Override
        public void close() throws IOException {
            super.close();
            readablePipe.close();
        }
    };
}

From source file:com.open.cas.shiro.util.ReflectionUtils.java

/**  
* ???  /*from   w w w. java  2 s.  c om*/
*  
* @param className  ??  
* @param methodName   ??  
* @param args   ?  
* @return   
* @throws Exception  
*/
public static Object invokeStaticMethod(final Class<?> ownerClass, final String methodName,
        final Class<?>[] parameterTypes, final Object[] args) {
    try {
        Method method = ownerClass.getMethod(methodName, parameterTypes);
        return method.invoke(null, args);
    } catch (Exception e) {
        throw convertReflectionExceptionToUnchecked(e);
    }
}

From source file:com.aurel.track.dbase.JobScheduler.java

private static void initializeJabDataMapsInJobs() {
    try {/*w  w  w .  ja v  a 2  s  .co  m*/
        for (String groupName : sched.getJobGroupNames()) {
            for (JobKey jobKey : sched.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

                String jobName = jobKey.getName();
                String jobGroup = jobKey.getGroup();

                JobDetail jobDetail = sched.getJobDetail(new JobKey(jobName, jobGroup));
                Class<?> jobClass = jobDetail.getJobClass();
                JobDataMap jobDataMap = jobDetail.getJobDataMap();
                try {
                    LOGGER.debug("Trying to call method in " + jobName);
                    Method setJobDataMapMethod = jobClass.getMethod("setJobDataMap", JobDataMap.class);
                    Object o = setJobDataMapMethod.invoke(null, jobDataMap);
                    LOGGER.debug("Called method in " + jobName);
                } catch (NoSuchMethodException nsme) {
                    // ignore
                } catch (InvocationTargetException ite) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(ite), ite);
                } catch (IllegalArgumentException e) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
                } catch (IllegalAccessException e) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
                } catch (Exception e) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
                }
            }
        }
    } catch (Exception e) {
        // ignore
    }
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

public static Method getMethod(Class<?> clazz, String name, Class<?>[] parameterTypes)
        throws NoSuchMethodException {
    return clazz.getMethod(name, parameterTypes);
}

From source file:com.linkedin.databus.bootstrap.utils.BootstrapSeederMain.java

public static void init(String[] args) throws Exception {
    parseArgs(args);/*from   w  w  w  . j  av  a2  s .  c  om*/

    // Load the source configuration JSON file
    //File sourcesJson = new File("integration-test/config/sources-member2.json");
    File sourcesJson = new File(_sSourcesConfigFile);

    ObjectMapper mapper = new ObjectMapper();
    PhysicalSourceConfig physicalSourceConfig = mapper.readValue(sourcesJson, PhysicalSourceConfig.class);
    physicalSourceConfig.checkForNulls();

    Config config = new Config();

    ConfigLoader<StaticConfig> configLoader = new ConfigLoader<StaticConfig>("databus.seed.", config);
    _sStaticConfig = configLoader.loadConfig(_sBootstrapConfigProps);

    // Make sure the URI from the configuration file identifies an Oracle JDBC source.
    String uri = physicalSourceConfig.getUri();
    if (!uri.startsWith("jdbc:oracle")) {
        throw new InvalidConfigException("Invalid source URI (" + physicalSourceConfig.getUri()
                + "). Only jdbc:oracle: URIs are supported.");
    }

    String sourceTypeStr = physicalSourceConfig.getReplBitSetter().getSourceType();
    if (SourceType.TOKEN.toString().equalsIgnoreCase(sourceTypeStr))
        throw new InvalidConfigException(
                "Token Source-type for Replication bit setter config cannot be set for trigger-based Databus relay !!");

    // Create the OracleDataSource used to get DB connection(s)
    try {
        Class oracleDataSourceClass = OracleJarUtils.loadClass("oracle.jdbc.pool.OracleDataSource");
        Object ods = oracleDataSourceClass.newInstance();
        Method setURLMethod = oracleDataSourceClass.getMethod("setURL", String.class);
        setURLMethod.invoke(ods, uri);
        _sDataStore = (DataSource) ods;
    } catch (Exception e) {
        String errMsg = "Error creating a data source object ";
        LOG.error(errMsg, e);
        throw e;
    }

    //TODO: Need a better way than relaying on RelayFactory for generating MonitoredSourceInfo
    OracleEventProducerFactory factory = new BootstrapSeederOracleEventProducerFactory(
            _sStaticConfig.getController().getPKeyNameMap());

    // Parse each one of the logical sources
    _sources = new ArrayList<OracleTriggerMonitoredSourceInfo>();
    FileSystemSchemaRegistryService schemaRegistryService = FileSystemSchemaRegistryService
            .build(_sStaticConfig.getSchemaRegistry().getFileSystem());

    Set<String> seenUris = new HashSet<String>();
    for (LogicalSourceConfig sourceConfig : physicalSourceConfig.getSources()) {
        String srcUri = sourceConfig.getUri();
        if (seenUris.contains(srcUri)) {
            String msg = "Uri (" + srcUri
                    + ") is used for more than one sources. Currently Bootstrap Seeder cannot support seeding sources with the same URI together. Please have them run seperately !!";
            LOG.fatal(msg);
            throw new InvalidConfigException(msg);
        }
        seenUris.add(srcUri);
        OracleTriggerMonitoredSourceInfo source = factory.buildOracleMonitoredSourceInfo(sourceConfig.build(),
                physicalSourceConfig.build(), schemaRegistryService);
        _sources.add(source);
    }
    _sSeeder = new BootstrapDBSeeder(_sStaticConfig.getBootstrap(), _sources);

    _sBootstrapBuffer = new BootstrapEventBuffer(_sStaticConfig.getController().getCommitInterval() * 2);

    _sWriterThread = new BootstrapSeederWriterThread(_sBootstrapBuffer, _sSeeder);

    _sReader = new BootstrapSrcDBEventReader(_sDataStore, _sBootstrapBuffer, _sStaticConfig.getController(),
            _sources, _sSeeder.getLastRows(), _sSeeder.getLastKeys(), 0);
}

From source file:azkaban.common.utils.Utils.java

/**
 * Get the named method from the class/*w  ww.  ja v a2  s .  com*/
 * 
 * @param c The class to get the method from
 * @param name The method name
 * @param argTypes The argument types
 * @return The method
 */
public static Method getMethod(Class<?> c, String name, Class<?>... argTypes) {
    try {
        return c.getMethod(name, argTypes);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(e);
    }
}