package com.logicbig.example.clazz;
import java.lang.reflect.Method;
public class GetDeclaredMethodExample {
public static void main(String... args) throws NoSuchMethodException {
Class<MyClass> c = MyClass.class;
Method m = c.getDeclaredMethod("aMethod");
System.out.println(m);
m = c.getDeclaredMethod("anotherMethod", int.class);
System.out.println(m);
}
private static class MyClass {
private void aMethod() { }
public void anotherMethod(int i) { }
}
}
Output
private void com.logicbig.example.clazz.GetDeclaredMethodExample$MyClass.aMethod()
public void com.logicbig.example.clazz.GetDeclaredMethodExample$MyClass.anotherMethod(int)
Attempting to access super class method:
package com.logicbig.example.clazz;
import java.lang.reflect.Method;
public class GetDeclaredMethodExample2 {
public static void main(String... args) throws NoSuchMethodException {
Class<MyClass> c = MyClass.class;
Method m = c.getDeclaredMethod("aSuperClassMethod");
System.out.println(m);
}
private static class MyClass extends TheSuperClass {}
private static class TheSuperClass {
public void aSuperClassMethod() {
}
}
}
Output
Caused by: java.lang.NoSuchMethodException: com.logicbig.example.clazz.GetDeclaredMethodExample2$MyClass.aSuperClassMethod()
at java.base/java.lang.Class.getDeclaredMethod(Class.java:2432)
at com.logicbig.example.clazz.GetDeclaredMethodExample2.main(GetDeclaredMethodExample2.java:14)
... 6 more
Method of an anonymous class:
package com.logicbig.example.clazz;
import java.lang.reflect.Method;
public class GetDeclaredMethodExample3 {
public static void main(String... args) throws NoSuchMethodException {
Runnable r = new Runnable() {
@Override
public void run() {
}
public void anotherMethod() {}
};
Method m = r.getClass().getDeclaredMethod("anotherMethod");
System.out.println(m);
}
}
Output
public void com.logicbig.example.clazz.GetDeclaredMethodExample3$1.anotherMethod()