Class.getMethods()

I have the following code:import java.io.*;
import java.lang.reflect.*;
public class Reflection
   public static void main(String[] args)
      Object object = null;
      System.out.print("Enter the name of the class: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      try
         String className = br.readLine();
         object = Class.forName(className).newInstance();
         showMethods(object);
      catch (Exception e) { }
   public static void showMethods(Object passedObject)
      Method[] methods = passedObject.getClass().getMethods();
      for (int x = 0 ; x < methods.length ; x++)
         System.out.println(methods[x]);
      System.out.print("\n" + passedObject.getClass().getName());
      System.out.println(" has access to " + methods.length + " methods.\n");
}If I enter "java.util.Vector" or "javax.swing.JFrame", I get the correct and expected response.
If I enter "java.math.BigDecimal" or "java.awt.event.ActionEvent", I get nothing.
Can anyone explain what I'm missing?
Thanx to one and all.

I'm beginning to think that, contrary to what the
docs say, there is no way to create and use an object
whose type is not known until runtime:Not entirely true.
You can find out what the available c'tors are, using reflection. You can pick one, give it some data, and call it. You can use reflection to invoke various methods on that object.
However, as we've been trying to explain, that's mostly rather pointless.
Say you set this all up. At runtime you get com class com.acme.RATO. You've never heard of this class before. At compile time, when you're writing the code that will invoke a c'tor and some methods on this class.
Which c'tor will you invoke? What args will you pass it? Which methods will you invoke? What args? Why?
Now, I say mostly pointless because you don't have to know at compile time which c'tors, methods, args to use. For something like [url http:/www.beanshell.org]BeanShell, the user provides that stuff at runtime.

Similar Messages

  • How to use the Class.getMethod(String name, Class[] paramArrays)

    Hi,
    I've a problem with the .getMethod method. I've search solutions in the tutorials but I haven't found sorry.
    I'm trying to copy a method from a Class named carre in a reference named m. But I don't understand the second part of the parameters. How can I write parameters in a Class array ?
    Method m = Carre.class.getMethod("getYou", args) ; //It doesn't work, because args is a String array, not a Class array, my parameters would be double.
    Could you help me ? Thanks for answers.

    Class[] classArray = { new Double().getClass(), new String().getClass()};That's not what you want to write. That generates two objects unnecessarily. You should write:new Class[] { Double.class, String.class };

  • Forums - How to use java.lang.Class.getMethod() and java.lang.reflect.Metho

    I have similar question. I am trying to invoke a method with no parameters. I don't know how to do that. Can someone please help.
    for example.
    I have 2 methods.
    public void setMethod(String strPut){
    this.strPut = strPut;
    public String getMethod(){
    return strPut;
    Method method = objRef.class.getMethod("setMethod", new Class[]{String.class});
    Object objReturn = method.invoke(sqlWhere, new Object[] {"any String"});
    I can invoke setMethod but I don't know how to invoke getMethod().

    Hi
    Try using something like this...
    CustomClass objCustomClass = new CustomClass ();
    Class customClass = objCustomClass.getClass ();
    Method m = customClass.getMethod ("getMethodName", (Class[])null);
    String strContent = (String) m.invoke (objCustomClass, null);
    Thanks and regards,
    Pazhanikanthan. P

  • Class.getMethod using a superclass

    I'm trying to use Class.getMethod to retrieve a particular method, but it keeps returning NoSuchMethodException s when i use code similar to this example.
    try {
         Class<?> c = Class.forName("javax.swing.JFrame");
         Method m = c.getMethod("add",javax.swing.JButton.class);
    catch(Exception e) {
         e.printStackTrace();
    }I think it is unable to find the method because the add method takes a java.awt.Component, but is there any way around casting it to that? The method names and arguments are only provided at runtime, and the only solution I see is successive calls to Class.getSuperClass and testing the parameter over and over again to try to find the right method. This doesn't seem like a good solution, or even efficient, when considering the combinations you would have to attempt when given multiple parameters.
    Is there a better way to solve this than that?

    Hi,
    I do not see a solution like the one you are looking for (automatic matching). But what may be easier than your proposed solution of successive calls to getMethod() with different combinations of parameter types, and each call throwing NoSuchMethodExceptions, may be something like:
    - call getMethods()
    - iterate over all methods found
    - first matching names
    - for each matching name, check parameter type (of course not equality, but whether your type would fit the type expected by the method)
    - repeat for each parameter of current match
    - repeat until matching method is found
    Bye.

  • How to use java.lang.Class.getMethod() and java.lang.reflect.Method.invoke(

    I want to call a specified method of one class dynamically. I use the method
    "getMethod()" in package "java.lang.Class" to get method and "invoke()" in
    " java.lang.reflect.Method " to invoke method.
    The problem is as following :
    1. There are two argument in this method "getMethod(String MethodName , Class[] paremterTypes)" in package "Class". I have no idea about the second parameter " Class[] parameterTypes ".what does the argument exactly mean ?
    2. There are two argument in the method "invoke(object obj, object[] obj)" in package "Method".
    I have no idea about the second parameter "object[] obj ".what is mean ?
    I pass " null " value to it and it works.But i pass anothers ,jvm will throw exception.

    I have a generic Method Executer that has a method like
    public Object execute(String className, String methodName, Object args)
        String fullClassName = packageName + className ;
        Class delegateClass = Class.forName(fullClassName);
        BaseDelegate delegate = (BaseDelegate)delegateClass.newInstance();
        Method method = null;
        if (args == null)
            method = delegateClass.getMethod(methodName, new Class[] {});
            obj = method.invoke(delegate,new Object[] {});
        else
            method = delegateClass.getMethod(methodName, new Class[] {args.getClass()});
            obj = method.invoke(delegate, new Object[]{args});
       }This seems to have problems when I call the method from a class like:
    execute("CategoryDelegate", "getCategoryById", new Integer(4144));(I get a NoSuchMethodException)
    The method I am trying to execute in CategoryDelegate looks like:
    public Category getCategoryById(int categoryId) throws DelegateExceptionI think it has to deal with the difference in the way we handle Primitive Wrappers and Objects. Wrapper we have to use Interger.TYPE and with the rest of the Objects we have to use obj.class.
    Am I doing something wrong here? Any suggestions to make it work for primitive wrappers as well as Objects?

  • How to load a class dynamically and then a call a method?

    Hi
    I want to call a method from a class,which class is loaded dynamically.
    Consider a classA and ClassB..
    ClassB contains a method showvalue() which returns a String value.
    I want to load a ClassB dynamically in ClassA,and call the method showvalue() and print the returned value of that method (showvalue).
    How to do this?
    Thanks

    Since you found your way to Reflections and Reference Objects, I can only assume you know that reflection is the answer. Since the reflection tutorial on this site, and indeed, the many others on the web, can explain this a whole lot better and more consisely than can be done in a forum, I'll point you in that direction instead. As a starting point, and to show I'm not just fobbing you off, you're interested in the classes java.lang.Class, java.lang.reflect.Method, and the method Class.getMethod(String, Class[])

  • How can i access the methods if i only got the java class file?

    just like what the topic said...i would like to ask if i only got the class file of java without API documentation. how can i know what method is included ?
    thanks a lot.
    my email address is : [email protected]

    Class.getMethods()
    throws SecurityException
    Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents an array class, primitive type, or void.

  • This class is missing.

    This is in continuation with my previous mail
    com.bea.wlw.netui.util.logging.StrutsLogFactory. the server throws an exception
    that the above class not found. any solution for ths

    I'd suggest posting in the workshop newsgroup. It looks like you're
    missing some workshop classes which shouldn't happen if this is a
    workshop-enabled domain.
    -- Rob
    Brian H wrote:
    We are trying to deploy running 8.1 SP2 and we get the same error (below). Our
    domain is workshop enabled. Any ideas?
    Thanks in advance!
    Exception:weblogic.management.ApplicationException: prepare failed for netuix.jar
    Module: netuix.jar Error: Exception preparing module: EJBModule(netuix.jar,status=NEW)
    Unable to deploy EJB: D:\Stage\netuix.jar from netuix.jar: weblogic.ejb20.WLDeploymentException:
    [EJB:010106]EJB : PortalCustomizationManager .Unable to initialize method info
    for remote or home interface. The error is java.lang.ClassNotFoundException: com.bea.netuix.application.exception.ObjectNotFoundException
    at java.lang.reflect.Method.resolve()V(Native Method) at java.lang.reflect.Method.<init>(I)V(Unknown
    Source) at java.lang.reflect.LangReflectImpl.newMethod(I)Ljava.lang.reflect.Method;(Unknown
    Source) at COM.jrockit.reflect.MemberAccess.newMethod(I)Ljava.lang.reflect.Method;(Unknown
    Source) at java.lang.Class.findCreateMethod(Ljava.util.HashMap;I)Ljava.lang.reflect.Method;(Unknown
    Source) at java.lang.Class.findMethods(I)[Ljava.lang.reflect.Method;(Unknown Source)
    at java.lang.Class.getMethods(I)[Ljava.lang.reflect.Method;(Unknown Source) at
    weblogic.ejb20.deployer.ClientDrivenBeanInfoImpl.initializeMethodInfos()V(ClientDrivenBeanInfoImpl.java:1224)
    at
    Rob Woollen <[email protected]> wrote:
    This must be a Workshop application.  Make sure you're using a >>workshop-enabled domain.  If you're still having problems, I'd suggest>>>>posting in the workshop newsgroup.>>>>-- Rob>>>>Senthil Kumar M Rangaswamy wrote:>>>>> This is in continuation with my previous mail >>>com.bea.wlw.netui.util.logging.StrutsLogFactory. the server throws>>>>an exception>>>>>that the above class not found. any solution for ths>>>>>>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

  • WDP calling EJB and passing objects of classes from Java project

    Hi.
    We have <b>Java</b> project which contains some classes common for all projects (like xxx.Version).
    We have <b>EJB</b> project which defines EJB interface using these common classes (like getVersion(String,int): xxx.Version and getCurrency(String,xxx.Version,int):xxx.Currency ).
    We have <b>Web Dynpro</b> project which calls EJB:
    1. Lookup is successful
    2. call to getVersion is successful
    3. call to getCurrency fails with <b>NoSuchMethodException</b>:
    xxx.XXXObjectImpl0.getCurrency(java.lang.String, xxx.Version, int)
         at java.lang.Class.getMethod(Class.java:986)
         at com.sap.engine.services.rmi_p4.reflect.LocalInvocationHandler.invokeInternal(LocalInvocationHandler.java:51)
         at com.sap.engine.services.rmi_p4.reflect.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:53)
         at $Proxy346.getCurrency(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.sap.engine.services.ejb.session.stateless_sp5.ObjectStubProxyImpl.invoke(ObjectStubProxyImpl.java:187)
         at $Proxy347.getCurrency(Unknown Source)
         at xxx.XXX.getCurrencyWrapper(XXXXX.java:24)
    How can I set dependencies to get this running?
    Thanks to all
           Volker

    Hi,
    Is it available in the interface you are using..
    If the answer is yes.. you might have probably forgotten to deploy the EJBs ear file after making the changes..
    Rebuild it.. and deploy the EJB s ear file again..
    It will solve the problem.. If that also does not work,it might be a problem with the cache.. restart the server..
    It should work now !
    Regards
    Bharathwaj

  • Interfaces and methods of Object class

    JSL 2.0 states the following
    If an interface has no direct superinterfaces, then the interface implicitly
    declares a public abstract member method m with signature s, return type r,
    and throws clause t corresponding to each public instance method m with
    signature s, return type r, and throws clause t declared in Object, unless a
    method with the same signature, same return type, and a compatible throws
    clause is explicitly declared by the interface.
    But the following codes produces empty output
    package test;
    import java.lang.reflect.Method;
    public class TestIterface {
        public static void main(String [] args){
            Method [] methods=Y.class.getMethods();
            for(int i=0, n=methods.length;i<n;i++)
                System.out.println(methods);
    interface Y{
    What are the reasons of such behaviour?

    then the interface implicitly declares a public abstract member method
    "Implicit" means that it's implied that the interface declares those methods; unlike java.lang.Object, there is no interface from which all other interfaces descend. All interfaces at the "top" of the inheritance hierarchy are implied to expose at least the same methods as Object.
    Hope this helps...

  • Exception in Class class native method

    Hi Guys,
    I am getting an Exception in the Class class native method getMethod0. The Exception is java.lang.NoSuchMethodException. Can some put light on this, as to why is this coming???
    Here's the starckTrace........
    java.lang.NoSuchMethodException
         at java.lang.Class.getMethod0(Native Method)
         at java.lang.Class.getMethod(Class.java:888)
         at com.gepower.gees.vc.utility.VCComparator.compare(VCComparator.java:67)
         at java.util.Arrays.mergeSort(Arrays.java:1181)
         at java.util.Arrays.mergeSort(Arrays.java:1189)
         at java.util.Arrays.mergeSort(Arrays.java:1189)
         at java.util.Arrays.mergeSort(Arrays.java:1188)
         at java.util.Arrays.mergeSort(Arrays.java:1189)
         at java.util.Arrays.mergeSort(Arrays.java:1189)
         at java.util.Arrays.mergeSort(Arrays.java:1188)
         at java.util.Arrays.sort(Arrays.java:1128)
         at java.util.Collections.sort(Collections.java:121)
    Thanx,
    Chandan.

    Class.getMethod() throws that exception if the method that is being searched for does not exist.
    And VCComparator.compare() used Class.getMethod().
    So something is wrong in VCComparator.compare().

  • Event triggering changes back to consumer class

    Hi all, newbie at Java and I hope you can give me a hand on this.
    Suppose I have 2 classes A and B. A has an instance of B, an event takes place in B and is caught by a listener in B.
    Can the listener call a method in A? I cant see how this can be done since B hasnt a handle to A.
    Many thanks...Peter

    It is cleaner to use an inner class if only the containing class will be using it. However, it's common to have listeners (especially those that are resued) as a separate class.
    You can either use reflection (see Class.getMethods()) or something like this:
    If all classes that can potentially have the method you're referring to implement an interface that declares the method, you can just blindly call the method. If it doesn't make sense for a given class to implement the behavior, you can leave the implementation blank.
    For example:
    public interface I {
        void doIt();
    // source of an event
    public class A implements I {
        public void doIt() {
            // do something special
            // code goes here
    // source of an event
    public class C implements I {
        public void doIt() {
            // do nothing
    // the listener
    public class B {
        public void actionPerformed( Event e ) {
            I source = (I) e.getSource();
            source.doIt();
    }In the above case, when the event originates from A, "code goes here" gets executed. When the event originates from C, doIt() still gets called, but the method doesn't do anything.
    From a responsibility point of view, deciding what to do lies with A and C, and when to do it with B.

  • Unable to connect to Tomcat from Java Class

    Hello,
    This is going to be long, so please bare with me.
    I have a Tomcat 5.5 on my Windows 7 machine.
    I run the Tomcat by executing the startup.bat under the bin folder. After the Tomcat is up, I am able to access the Tomcat's home page by browsing to: http://localhost:8080.
    My problem is this:
    I wrote a short Java application that tries to access the same address (http://localhost:8080) using a URL. The code listed below:
    try {
         URL url = new URL("http://localhost:8080");
         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
         String inputLine;
         while ((inputLine = in.readLine()) != null) {
              // Process each line.
              System.out.println(inputLine);
         in.close();
    } catch (MalformedURLException me) {
         me.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    When I run the program I get the following exception:
    java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
         at java.net.Socket.connect(Socket.java:520)
         at java.net.Socket.connect(Socket.java:470)
         at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
         at sun.net.www.http.HttpClient.openServer(HttpClient.java:387)
         at sun.net.www.http.HttpClient.openServer(HttpClient.java:522)
         at sun.net.www.http.HttpClient.<init>(HttpClient.java:231)
         at sun.net.www.http.HttpClient.New(HttpClient.java:304)
         at sun.net.www.http.HttpClient.New(HttpClient.java:321)
         at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:813)
         at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:765)
         at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:690)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:934)
         at java.net.URL.openStream(URL.java:1007)
         at test.xpolog.URLTest.main(URLTest.java:14)
    What I've come up with until now is the following:
    1) If I replace localhost with any other external host (such as www.cnn.com), the code works (I see the HTML printed out).
    2) If I replace localhost with [::1], the code works. * Comment about this item follows the list of items.
    3) If I run the same code on a Windows XP machine running the same Tomcat, the code works.
    4) If I run the same code on a Windows XP machine, with only replacing localhost with the address of the Windows 7 machine running the same Tomcat, the code works.
    * Comment about item #2 (I'm not sure this has something to do with the problem):
    When I run netstat -ao on the Windows 7 machine, I see the following lines regarding the Tomcat port (8080):
    Proto Local Address Foreign Address State PID
    TCP [::]:8080 [::]:0 LISTENING 5204
    TCP [::1]:8080 [::1]:60821 TIME_WAIT 0
    My thoughts:
    1) Is this related to Windows 7?
    2) Is this related to the Tomcat configuration?
    3) Is this related to some component (not the Firewall, I have it disabled) blocking the connection?
    Any help regarding this strange problem would be appreciated.
    Thanks,
    Ziv

    > Thank you so much for your patience. It makes more sense now.
    Cool! You can think of it like this: JNI is roughly equivalent to the reflection API in the Java language:
    - jobject is a reference to a java.lang.Object;
    - jclass is a reference to a java.lang.Class;
    - methodID is like java.lang.reflect.Method or java.lang.reflect.Constructor;
    - fieldID is like java.lang.reflect.Field;
    - GetObjectClass () is like Object.getClass ();
    - FindClass () is like Class.forName ();
    - GetMethodID () and GetStaticMethodID () are like Class.getMethod ();
    - GetFieldID () and GetStaticFieldID () are like Class.getField ();
    - Call<Type>Method () and CallStatic<Type>Method () are like Method.invoke ();
    - NewObject () is like Constructor.newInstance ();
    - Get<Type>Field () and GetStatic<Type>Field () are like Field.get ();
    - Set<Type>Field () and SetStatic<Type>Field () are like Field.set ();
    So if you are familiar with reflection, just think in terms of how you would perform operations in the Java language using reflection, and then translate to the equivalent in JNI.
    > Which technique is better to use? GetFieldID/GetObjectField or GetMethodID/CallObjectMethod?
    I suggest design it as if coding in pure Java. Usually this means using getter methods rather than accessing fields directly, for all the usual OO benefits of encapsulation and polymorphism.
    -slj-

  • GetMethod(...) and polymorphism

    Hi,
    When trying to get a method by specifying not the formal parameter classes, but subclasses of it, one gets NoSuchMethodException. E.g. the add(Object) method from Collection doesn't work when one specifies Color in stead of Object as argument type.
    Is the only option to write code which tries all combinations of superclasses of all arguments, or are there better solutions?
    BA

    I had a bit of fun once writing something to mimic the compiler's method binding. The documentation explains that it isn't perfect, but if you really want to hack it, feel free. I'll make it publicly available with a request that anyone who modifies it to fix the current limitations post their fix here. package com.akshor.pjt33.utils;
    import java.lang.reflect.*;
    * A non-instantiable class providing static utility methods related to
    * reflection.
    * @specifier Peter Taylor
    * @implementer Peter Taylor
    public abstract class ReflectionUtils
         * This constructor cannot be called, as it prevents subclassing.
        private ReflectionUtils()
            throw new UnknownError();
         * Simulates the compile-time binding of a method-name and a list of
         * parameter types. Whereas <code>Class.getMethod(String, Class[])</code>
         * looks for methods with the exact signature, this looks through all the
         * applicable public methods of the specified class, and selects the most
         * specific.
         * <p>
         * Note that this method will currently throw an exception if there is more
         * than one maximally specific method, even if they all have the same
         * signature. This is not quite the same as the JLS 15.12.2.2. Consider the
         * case <pre>
         *     public interface A { public void method(); }
         *     public interface B { public void method(); }
         *     public abstract class C implements A, B { }
         *     getMethod(C, "method", new Class[0]);</pre>
         * @param clazz The class in which to seek the specified method.
         * @param methodName The name of the method to seek.
         * @param paramTypes The list of parameters.
         * @return The unique maximally specific method with respect to the
         *         specified class, name and parameter types.
         * @throws NoSuchMethodException if there isn't a unique maximally specific
         *                               method, or if the name is "&lt ;init&gt ;" or
         *                               "&lt ;clinit&gt ;". (Off to file bug about JDCF
         *                               handling of HTML entities in tags).
    * @throws IllegalArgumentException if any argument is null.
    * @throws SecurityException if access to the information is denied.
    * @see Class#getMethods()
    public static Method getMethod(Class clazz,
    String methodName,
    Class[] paramTypes)
    throws NoSuchMethodException
    // Check the arguments are all non-null.
    if (clazz == null || methodName == null || paramTypes == null)
    throw new IllegalArgumentException();
    // We don't need to check for <init> and <clinit>, because they're not
    // in the list of methods returned.
    // Since we assume a unique maximally specific method, we don't need to
    // store a Set of maximally specific methods.
    Method currentBestCandidate = null;
    // Iterate through the public methods of the class.
    Method[] candidates = clazz.getMethods();
    for (int i = 0; i < candidates.length; i++)
    // We discard non-applicable methods immediately.
    if (methodApplicable(candidates, methodName, paramTypes))
    // If the method is applicable, there are four cases:
    // 1. currentBestCandidate is null. Store candidates[i] there.
    // 2. currentBestCandidate is more specific than candidates[i].
    // Discard candidates[i].
    // 3. candidates[i] is more specific than currentBestCandidate.
    // Store it there.
    // 4. Neither candidates[i] nor currentBestCandidate is more
    // specific than the other. Throw an exception.
    // (Note: the JLS solution would be to case-split again: if
    // both are concrete, throw the exception; if one is
    // concrete, select that one; if both are abstract, pick one
    // arbitrarily. However, in the latter case we really want a
    // new Method whose thrown checked exceptions are formed by
    // intersection of the thrown checked exceptions of the two
    // abstract methods - and since Method doesn't provide any
    // protected or public constructors, we can't provide such a
    // Method. This is why we throw an exception).
    if (currentBestCandidate == null ||
    methodMoreSpecific(candidates[i], currentBestCandidate))
    // candidates[i] is the new current best candidate.
    currentBestCandidate = candidates[i];
    else if (!methodMoreSpecific(currentBestCandidate,
    candidates[i]))
    // Neither method is more specific than the other.
    throw new NoSuchMethodException("Ambiguity");
    // If we have a best candidate, that's the method to return.
    if (currentBestCandidate != null)
    return currentBestCandidate;
    // No such method found. Pity.
    throw new NoSuchMethodException("No applicable public method");
    * Checks whether or not a method is applicable to a method call. This is so
    * iff the name is correct, the number of parameters is correct, and each of
    * the call's parameter types is assignable to the method's corresponding
    * parameter type.
    * @param m The method to check for applicability.
    * @param name The required method name.
    * @param paramTypes The required parameter types.
    * @return Whether or not the method is applicable to the name and parameter
    * types.
    * @throws IllegalArgumentException if any parameter is null.
    private static boolean methodApplicable(Method m,
    String name,
    Class[] paramTypes)
    // Check the parameters are non-null.
    if (m == null || name == null || paramTypes == null)
    throw new IllegalArgumentException();
    // Check that the name corresponds.
    if (!m.getName().equals(name))
    return false;
    // Get the parameter types of the method, and check that the number of
    // parameters corresponds.
    Class[] actualParamTypes = m.getParameterTypes();
    if (actualParamTypes.length != paramTypes.length)
    return false;
    // Check that all of the parameter types are assignable.
    for (int i = 0; i < paramTypes.length; i++)
    if (!actualParamTypes[i].isAssignableFrom(paramTypes[i]))
    return false;
    // All tests pass.
    return true;
    * Checks whether or not the first parameter is more specific than the
    * second parameter. This is the case iff the declaring class of
    * <code>more</code> is assignable to the declaring class of
    *<code>less</code> and each of the parameters of <code>more</code> is
    * assignable to the corresponding parameter of <code>less</code>. (The
    * observant will notice that the test is a &ge; rather than a > test).
    * @param more The method to check for being more specific.
    * @param less The method to check for being less specific.
    * @return Whether or not <code>more</code> is more specific than
    * <code>less</code>.
    * @throws IllegalArgumentException if either parameter is null, or if they
    * have different names or numbers of
    * parameters.
    private static boolean methodMoreSpecific(Method more, Method less)
    // Check that both of the parameters are non-null.
    if (more == null || less == null)
    throw new IllegalArgumentException("Null parameter");
    // Check that they have the same names.
    if (!more.getName().equals(less.getName()))
    throw new IllegalArgumentException("Different names");
    // Get their parameter types and check that they have the same number of
    // parameters.
    Class[] moreParamTypes = more.getParameterTypes();
    Class[] lessParamTypes = less.getParameterTypes();
    if (moreParamTypes.length != lessParamTypes.length)
    throw new IllegalArgumentException("Different numbers of params");
    // To be more specific, more needs to have a declaring class assignable
    // to that of less.
    if (!less.getDeclaringClass().isAssignableFrom(
    more.getDeclaringClass()))
    return false;
    // To be more specific, more has to have parameters assignable to the
    // corresponding parameters of less.
    for (int i = 0; i < moreParamTypes.length; i++)
    if (!lessParamTypes[i].isAssignableFrom(moreParamTypes[i]))
    return false;
    // All tests passed.
    return true;

  • Class Methods throught Reflect

    Is it necessary to execute the Class.getMethods() method to retrieve the methods with a certain name?
    For example :
    public class XPTO{
    public void test(int i){}
    public void test(String str){}
    public void test(long l){}
    }I just need the test methods, but the getMethods() returns besides the looked for methods, also the inhereted methods and other defined methods in the actual Class.
    In this case the class just has a couple of methods, now lets imagine a javax.swing.JComponent subclass... with more implemented methods in it.
    Well you may say it fast to process a search, or filter for the methods, but lets imagine that it's necessary to process this type of action for thousands of Class's (a little extremist?!? Maybe).
    Daniel Campelo

    then there is no other way than going through all
    methods, unless those methods are part of a certain
    (smaller) interface or are being declared in a known
    class, in which case you could use
    getDeclaredMethods() of that certain class.In the given example i was searching for methods that were defined in the processed class but there can be methods defined in the super class...And the intention is to retreave all methods that correspond to a given name that a certain class has defined (or it's super class's).
    however, I don't think that going through all method
    names will be a bottleneck for your application...It may be true for a couple of class's with not many methods defined but like i said : '(...)lets imagine that it's necessary to process this type of action for thousands of Class's(...)'.
    Many milliseconds make seconds that in turn make minutes and so on...
    I'll teste it and will report back...
    Thanx for the help so far :)
    Daniel Campelo

Maybe you are looking for

  • How to install BI Publisher 10.1.3.4.2 on Windows 2008 R2

    Hi experts Refering to the document Oracle® Business Intelligence Publisher Certification Information 10g Release 3 (10.1.3.4.2) E12692-08 To install on Windows 2008 R2 follow the steps in "Manually Installing BI Publisher to a J2EE Application Serve

  • UCMDB Excel import - update/delete relationship

    Hi, is any solution to update or delete a relationship between the object in Excel import? I created one (excel import), but there are wrong way in the relationship, so I want to change/update or delete all wrong, and create the good . Anyone have an

  • Exception in java.io.UnixFileSystem.getBooleanAttributes0

    Hi All, I am seeing this stack trace, when running an application inside JBOSS: at java.io.UnixFileSystem.getBooleanAttributes0(Native Method) at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:221) at java.io.File.isDirectory(File.ja

  • FDM Mapping script produces result #script

    Hello, I am trying to use the following mapping script and instead of getting the result defined in the script it is producing the result #script. It is as if it is taking that as the target rather than processing the script. Has anyone else seen thi

  • Spell Checker in DW CC 2014.1 Release

    Why is the spell checker not working with Fluid Grid Layouts?