试试这个。
public class MethodCallRecognization {
public static void main(String[] args) {
MethodContainerC methodContainerC = new MethodContainerC();
methodContainerC.display();
// I want to know here
String className=getClassName(methodContainerC.getClass(), "display") ;
System.out.println(className);
}
public static String getClassName(Class c,String methodName){
Method m[]=c.getDeclaredMethods();
for(Method m1:m){
if(m1.getName().equals(methodName)){
return c.getName();
}
}
return getClassName(c.getSuperclass(),methodName);
}
}
如果方法被重载,您还需要检查参数类型而不是名称。但这应该给你的想法。
根据评论这里是更好的版本getClassName
public static String getClassname(Class c, String methodName){
try{
Method m= c.getDeclaredMethod( methodName);
return c.getName();
}catch(NoSuchMethodException nse){
return getClassName(c.getSuperclass(),methodName);
}
}
如果 dsiplay 方法采用参数,则
public class MethodCallRecognization {
public static void main(String[] args) {
MethodContainerC methodContainerC = new MethodContainerC();
methodContainerC.display("" , "");//Suppose it takes String id and String name parameter
// I want to know here
Class[] parametertype={String.class,String.class};
String className=getClassName(methodContainerC.getClass(), "display", parametertype) ;
System.out.println(className);
}
public static String getClassname(Class c, String methodName, Class[] parametertype){
try{
Method m= c.getDeclaredMethod( methodName, parametertype);
return c.getName();
}catch(NoSuchMethodException nse){
return getClassName(c.getSuperclass(),methodName, parametertype);
}
}
}