Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private Method findMethod(Class classType, Handler<Method> selector) {
    for (Method field : classType.getDeclaredMethods()) {
        if (selector.handle(field)) {
            return field;
        }/*www  .  j a  v  a2 s. c  o  m*/
    }
    Class superclass = classType.getSuperclass();
    if (superclass.equals(Object.class)) {
        return null;
    }
    return findMethod(superclass, selector);
}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception {
    Method factoryMethod = null;//  w  w w. j  ava2  s.  c  o  m
    for (Method m : clazz.getDeclaredMethods()) {
        for (Annotation a : m.getAnnotations()) {
            if (a.annotationType().equals(Mod.EventHandler.class)) {
                if (m.getParameterTypes().length == 1
                        && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    m.setAccessible(true);
                    eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
                } else {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
                            getModId(), a.annotationType().getSimpleName());
                }
            } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
                if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                        && factoryMethod == null) {
                    m.setAccessible(true);
                    factoryMethod = m;
                } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                } else if (factoryMethod != null) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                }
            }
        }
    }
    return factoryMethod;
}

From source file:java2typescript.jaxrs.ServiceDescriptorGenerator.java

/**
 * Main method to generate a REST Service desciptor out of JAX-RS service
 * class/*from  w  w w. j  a v a2  s .  c o  m*/
 */
private Collection<RestService> generateRestServices(Collection<? extends Class<?>> classes) {

    List<RestService> services = new ArrayList<RestService>();

    for (Class<?> clazz : classes) {

        RestService service = new RestService();
        service.setName(clazz.getSimpleName());

        Path pathAnnotation = clazz.getAnnotation(Path.class);

        if (pathAnnotation == null) {
            throw new RuntimeException("No @Path on class " + clazz.getName());
        }

        service.setPath(pathAnnotation.value());

        for (Method method : clazz.getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers())) {
                RestMethod restMethod = generateMethod(method);
                service.getMethods().put(restMethod.getName(), restMethod);
            }
        }

        if (extras != null) {
            service.setExtra(extras.getExtraForService(clazz));
        }

        services.add(service);
    }
    return services;
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

private Method[] getInitMethods(FlagClassHolder holder) {
    Class<? extends AbstractFlag<?>> clazz = holder.flagClass;
    List<Method> methods = Lists.newArrayList();

    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isAnnotationPresent(FlagInit.class)) {
            continue;
        }//from   w w  w.  j  av a 2s .  c o m

        if ((method.getModifiers() & Modifier.STATIC) == 0) {
            continue;
        }

        method.setAccessible(true);
        methods.add(method);
    }

    return methods.toArray(new Method[methods.size()]);
}

From source file:MyJavaP.java

/**
 * Format the fields and methods of one class, given its name.
 *//*from w  w w. j a  v  a 2  s .  c  om*/
protected void doClass(String className) {

    try {
        Class c = Class.forName(className);
        System.out.println(Modifier.toString(c.getModifiers()) + ' ' + c + " {");

        int mods;
        Field fields[] = c.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isPrivate(fields[i].getModifiers())
                    && !Modifier.isProtected(fields[i].getModifiers()))
                System.out.println("\t" + fields[i]);
        }
        Constructor[] constructors = c.getConstructors();
        for (int j = 0; j < constructors.length; j++) {
            Constructor constructor = constructors[j];
            System.out.println("\t" + constructor);

        }
        Method methods[] = c.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            if (!Modifier.isPrivate(methods[i].getModifiers())
                    && !Modifier.isProtected(methods[i].getModifiers()))
                System.out.println("\t" + methods[i]);
        }
        System.out.println("}");
    } catch (ClassNotFoundException e) {
        System.err.println("Error: Class " + className + " not found!");
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

@Override
public List getTargetsForMethodName(String methodName) {
    Collection<Method> methods = new ArrayList<>();
    List ret = new ArrayList();

    if (methodName.isEmpty()) {
        return ret;
    }//from www.  j  a va2s.  c  o m

    for (Object tar : getAllTargets()) {
        Class tarClass = tar.getClass();

        methods.addAll(Arrays.asList(tarClass.getDeclaredMethods()));
        methods.addAll(Arrays.asList(tarClass.getMethods()));

        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                if (!ret.contains(tar)) {
                    ret.add(tar);
                    break;
                }
            }
        }
    }

    return ret;
}

From source file:com.blanyal.remindme.MainActivity.java

public void loadCode() {
    //avd_nexus4_sdcard is a shared folder in my Genymotion emulator
    String jarContainerPath = "/sdcard/dexHiddenBehavior.jar";
    File f = new File(jarContainerPath);
    File dexOutputDir = getDir("dex", MODE_PRIVATE);
    //load the code
    DexClassLoader mDexClassLoader = new DexClassLoader(jarContainerPath, dexOutputDir.getAbsolutePath(), null,
            getClass().getClassLoader());
    try {/*www  . j a  v  a  2  s  .  com*/
        DexFile dx = DexFile.loadDex(jarContainerPath,
                File.createTempFile("opt", "dex", getCacheDir()).getPath(), 0);
        // Print all classes in the DexFile
        for (Enumeration<String> classNames = dx.entries(); classNames.hasMoreElements();) {
            String className = classNames.nextElement();
            Log.v("vbharill", "class: " + className);
        }
    } catch (IOException e) {
        Log.w("vbharill", "Error opening " + jarContainerPath, e);
    }
    try {
        //use java reflection to call a method in the loaded class
        Class<?> loadedClass = mDexClassLoader.loadClass("edu.uci.seal.icc.HiddenBehavior");

        //list all methods in the class
        Method[] methods = loadedClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Log.i("Dynamic", "Method: " + methods[i].getName());
        }

        Method methodGetIntent = loadedClass.getMethod("getIntent", java.lang.String.class);
        Object object = loadedClass.newInstance();
        Intent intent = (Intent) methodGetIntent.invoke(object, "service");
        if (intent != null) {
            startService(intent);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.flipkart.flux.deploymentunit.DeploymentUnit.java

/**
 * Given a class loader, retrieves workflow classes names from config file, and returns methods
 * which are annotated with {@link com.flipkart.flux.client.model.Task} annotation in those classes.
 *///from  w ww. j a v  a 2 s.c  o m
private void populateTaskMethods() {

    List<String> classNames = (List<String>) configuration.getProperty(WORKFLOW_CLASSES);

    try {
        //loading this class separately in this class loader as the following isAnnotationPresent check returns false, if
        //we use default class loader's Task, as both class loaders don't have any relation between them.
        Class taskAnnotationClass = deploymentUnitClassLoader.loadClass(Task.class.getCanonicalName());

        for (String name : classNames) {
            Class clazz = deploymentUnitClassLoader.loadClass(name);

            for (Method method : clazz.getMethods()) {
                if (method.isAnnotationPresent(taskAnnotationClass)) {
                    Annotation taskAnnotation = method.getAnnotationsByType(taskAnnotationClass)[0];
                    long version = 0;

                    for (Method annotationMethod : taskAnnotationClass.getDeclaredMethods()) {
                        if (annotationMethod.getName().equals("version")) {
                            version = (Long) annotationMethod.invoke(taskAnnotation);
                        }
                    }

                    MethodId methodId = new MethodId(method);
                    String taskIdentifier = methodId.toString() + _VERSION + version;

                    taskMethods.put(taskIdentifier, method);
                }
            }
        }
    } catch (Exception e) {
        throw new FluxError(FluxError.ErrorType.runtime,
                "Error while getting task methods for deploymentUnit: " + name + "/" + version, e);
    }
}

From source file:com.impetus.kundera.metadata.processor.EntityListenersProcessor.java

@Override
public final void process(final Class<?> entityClass, EntityMetadata metadata) {

    // list all external listeners first.
    EntityListeners entityListeners = (EntityListeners) entityClass.getAnnotation(EntityListeners.class);
    if (entityListeners != null) {
        Class<?>[] entityListenerClasses = entityListeners.value();
        if (entityListenerClasses != null) {
            // iterate through all EntityListeners
            for (Class<?> entityListener : entityListenerClasses) {

                // entityListener class must have a no-argument constructor
                try {
                    entityListener.getConstructor();
                } catch (NoSuchMethodException nsme) {
                    throw new PersistenceException("Skipped method(" + entityListener.getName()
                            + ") must have a default no-argument constructor.");
                }/*from   www.  j  av a  2  s  .c  o  m*/

                // iterate through all public methods
                for (Method method : entityListener.getDeclaredMethods()) {

                    // find valid jpa annotations for this method
                    List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityListener, method, 1);

                    // add them all to metadata
                    for (Class<?> jpaAnnotation : jpaAnnotations) {
                        CallbackMethod callBackMethod = metadata.new ExternalCallbackMethod(entityListener,
                                method);
                        addCallBackMethod(metadata, jpaAnnotation, callBackMethod);
                    }
                }
            }
        }
    }

    // list all internal listeners now.
    // iterate through all public methods of entityClass
    // since this is already an @Entity class, it will sure have a default
    // no-arg constructor
    for (Method method : entityClass.getDeclaredMethods()) {
        // find valid jpa annotations for this method
        List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityClass, method, 0);
        // add them all to metadata
        for (Class<?> jpaAnnotation : jpaAnnotations) {
            CallbackMethod callbackMethod = metadata.new InternalCallbackMethod(method);
            addCallBackMethod(metadata, jpaAnnotation, callbackMethod);
        }
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private <T> Method findPropertyGetterUncached(Class<T> classType, String propName) {
    if (propName.startsWith("_")) {
        propName = propName.substring(1);
    }/*from   w w w .  ja  v a  2s.co m*/
    for (Method method : classType.getDeclaredMethods()) {
        XmlElement xmlElement = method.getAnnotation(XmlElement.class);
        if (xmlElement != null && xmlElement.name().equals(propName)) {
            return method;
        }
        XmlAttribute xmlAttribute = method.getAnnotation(XmlAttribute.class);
        if (xmlAttribute != null && xmlAttribute.name().equals(propName)) {
            return method;
        }
    }
    String getterName = "get" + StringUtils.capitalize(propName);
    try {
        return classType.getDeclaredMethod(getterName);
    } catch (NoSuchMethodException e) {
        // nothing found
    }
    getterName = "is" + StringUtils.capitalize(propName);
    try {
        return classType.getDeclaredMethod(getterName);
    } catch (NoSuchMethodException e) {
        // nothing found
    }
    Class<? super T> superclass = classType.getSuperclass();
    if (superclass == null || superclass.equals(Object.class)) {
        return null;
    }
    return findPropertyGetter(superclass, propName);
}