Java使用外部上下文调用静态方法/检查递归方法

Java使用外部上下文调用静态方法/检查递归方法,java,recursion,reflection,jvm,Java,Recursion,Reflection,Jvm,我想检查一个方法是否使用递归。所以我写了这个模型: public class Main { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = Child.class.getMethod("toBeTested", int.class

我想检查一个方法是否使用递归。所以我写了这个模型:

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = Child.class.getMethod("toBeTested", int.class);
        Object result = method.invoke(Super.class, 5);
        System.out.println((Integer) result);
    }
}


public class Super extends Child{

    public static int toBeTested(int a){
        System.out.println("validating recursion");
        return Child.toBeTested(a);
    }
}


public class Child {

    public static int toBeTested(int a){
        if(a==0)return 0;
        return toBeTested(a-1)+1;
    }
}

因此,我尝试在具有Super.class上下文的Child中执行该方法,希望在递归中它将调用Super::toBeTested,因此我可以验证该方法是否使用递归


这可能是我尝试的方式吗?如果没有,为什么不呢?检查外部代码的递归的其他想法…

不,你不能这样做,因为静态方法不是这样工作的,它们没有一个“上下文”来决定它们在运行时调用什么,而是在编译时决定的(除非你想把类加载器称为上下文)

如果是非静态方法,则可以执行以下操作:

public static class Child extends Super {

    public int toBeTested(int a){
        System.out.println("validating recursion");
        return super.toBeTested(a);
    }
}


public static class Super {

    public int toBeTested(int a){
        if(a==0)return 0;
        return toBeTested(a-1)+1;
    }
}

public static void main(String args[]) throws Exception {
    Method method = Super.class.getMethod("toBeTested", int.class);
    Object result = method.invoke(new Child(), 5);
    System.out.println((Integer) result);
}
它将打印验证递归的
6次,因为要调用的方法取决于对象的运行时类型

要检查静态方法是否调用自己,您可以读取该方法的字节码(如果您有权访问它)