可以通过使用反射来实现按顺序调用方法,并排除一个特定的父类的方法。下面是一个示例代码,其中包含一个Parent类和两个Child类,每个Child类继承了Parent类并添加了一个新方法。我们可以通过创建一个方法列表并按序调用它们(除了特定父类的方法)来实现按顺序调用方法。
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
class Parent {
public void method1() {
System.out.println("Parent method1");
}
public void method2() {
System.out.println("Parent method2");
}
}
class Child1 extends Parent {
public void method3() {
System.out.println("Child1 method3");
}
}
class Child2 extends Parent {
public void method4() {
System.out.println("Child2 method4");
}
}
public class Main {
public static void main(String[] args) {
List methodList = new ArrayList<>();
// Add all the methods of Child1
for(Method method: Child1.class.getDeclaredMethods()) {
if(!method.getName().equals("method1")) {
methodList.add(method);
}
}
// Add all the methods of Child2
for(Method method: Child2.class.getDeclaredMethods()) {
if(!method.getName().equals("method2")) {
methodList.add(method);
}
}
// Add all the methods of Parent except method1
for(Method method: Parent.class.getDeclaredMethods()) {
if(!method.getName().equals("method1")) {
methodList.add(method);
}
}
// Call all the methods in order
for(Method method: methodList) {
try {
method.invoke(method.getDeclaringClass().newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在上面的例子中,我们创建了一个方法列表,并将除Parent类的method1之外的所有方法添加到列表中。我们可以使用反射调用方法,并在循环
下一篇:按顺序调用服务并使用结果中的参数