Java 使用外部上下文调用静态方法/检查递归方法
Java invoke static method with Foreign Context / Check method for recursion
我想检查一个方法是否使用递归。所以我写了这个模型:
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,因此我可以验证该方法使用递归。
我试过的方法是否可行?如果没有,为什么不呢?检查递归的外部代码的任何其他想法...
不,你不能那样做,因为静态方法不是这样工作的,它们没有决定它们在运行时调用什么的“上下文”,它是在编译时决定的(除非你想调用类加载器上下文)。
如果它是 non-static 方法,那么你可以这样做:
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);
}
它会打印 validating recursion
6 次,因为要调用的方法取决于对象的运行时类型。
要检查静态方法是否调用自身,您可以阅读该方法的字节码(如果您有权访问它)。
我想检查一个方法是否使用递归。所以我写了这个模型:
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,因此我可以验证该方法使用递归。
我试过的方法是否可行?如果没有,为什么不呢?检查递归的外部代码的任何其他想法...
不,你不能那样做,因为静态方法不是这样工作的,它们没有决定它们在运行时调用什么的“上下文”,它是在编译时决定的(除非你想调用类加载器上下文)。
如果它是 non-static 方法,那么你可以这样做:
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);
}
它会打印 validating recursion
6 次,因为要调用的方法取决于对象的运行时类型。
要检查静态方法是否调用自身,您可以阅读该方法的字节码(如果您有权访问它)。