Get public methods from a Java class

Question:

I need to get the list of public methods of a Java class, but I don't want to get the wait , toString , hasCode , etc, that the Java class inherits. I only want to get the public methods of that class, not those inherited from its superclass.

Is there any method in Java reflection to get only those methods?

Right now this is my code:

 String miclase;
 Class<?> clase;
 clase = Class.forName(miclase);
 Method[] allMethods = clase.getMethods();

And I don't want to get wait , wait , wait , equals , toString , hasCode , getClass , notify and notifyAll

UPDATE This is my code now after using the first of the answers and now it DOES NOT print the inherited methods or the private methods when I read the parameters of the methods:

String miclase; 
Class<?> clase; 
clase = Class.forName(miclase); 
Method[] allMethods = clase.getDeclaredMethods();
for (Method method : allMethods){
  if (Modifier.isPublic(method.getModifiers())) {
                    Parameter[] params = method.getParameters();
                    for (Parameter parametro : params) {
                        System.out.println("name: "+parametro.getName()+" type:" +parametro.getType());
                    }

                } }

Answer:

You could use getDeclaredMethods() which returns all the methods of the class, excluding the inherited ones. But it would not be only the public.

To filter the public you would have to use Modifier.isPublic(method.getModifiers()) for each method of the array.

Example:

Method[] methods = TuClase.class.getDeclaredMethods();
    for(Method method : methods) {
        if (Modifier.isPublic(method.getModifiers())) {
            System.out.println(method.getName());
        }
    }
}

Complete example with execution:

package prueba;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;

public class MiClase {

    public static void main(String[] args) throws ClassNotFoundException {

        String miclase = "prueba.MiClase";
        Class<?> clase;
        clase = Class.forName(miclase);
        Method[] allMethods = clase.getDeclaredMethods();
        for (Method method : allMethods) {
            if (Modifier.isPublic(method.getModifiers())) {
                Parameter[] params = method.getParameters();
                System.out.println("method: " + method.getName());
                for (Parameter parametro : params) {
                    System.out.println("param name: " + parametro.getName() + " type:" + parametro.getType());
                }

            }
        }

    }

    public void publico(int a, String b) {
    }

    private void privado(double c) {
    }
}

Result:

run:
method: publico
param name: arg0 type:int
param name: arg1 type:class java.lang.String
method: main
param name: arg0 type:class [Ljava.lang.String;
BUILD SUCCESSFUL (total time: 0 seconds)
Scroll to Top