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 the ones inherited from its superclass.
Is there any method in reflection
Java 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 the methods wait
, wait
, wait
, equals
, toString
, hasCode
, getClass
, notify
andnotifyAll
UPDATE This is my code now after using the first answer and now it does NOT print inherited methods or private methods anymore when I read method parameters:
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());
}
} }
You could use
getDeclaredMethods()
that returns all the methods of the class, excluding the inherited ones. But it would not be just the public.To filter the public you would have to use
Modifier.isPublic(method.getModifiers())
for each method of the array.Example:
Complete example with execution:
Result:
You can check that the method is declared in the relevant class: