如何使用注释参数优先级进行inove方法

时间:2018-06-18 08:59:09

标签: java reflection

如何使用注释参数优先级调用方法?

获得了testmethods,我应该用java反射调用:

public class Testmethods {

//There are eight method, should be invocen with value prioritet.
//First method(1), last method(8)

//first method
@Test(8)
public void method1(){
    System.out.println("test");
}
.
.
.
.
//last method
@Test(1)
public void method8(){
    System.out.println("test7");
}

带有int parametr优先级的Annottation类:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
    int value();
}

尝试使用循环调用它:

   private static void start(Class c) throws Exception {
        c = Testmethods.class;
        Method[] methods = c.getDeclaredMethods();

        int before = 0;
        int after = 0;
        int annoValue = 0;

        for (Method m : methods) {
            if (m.isAnnotationPresent(BeforeSuite.class)) {
                before++;
            }
            if (m.isAnnotationPresent(AfterSuite.class)) {
                after++;
            }

            if (m.isAnnotationPresent(BeforeSuite.class) && 
                before > COUNT || m.isAnnotationPresent(AfterSuite.class) && 
                after > COUNT) {
                throw new RuntimeException("more then one");
            }

            if (m.isAnnotationPresent(BeforeSuite.class) && 
                m.getAnnotation(BeforeSuite.class).value() == 10) {
                m.invoke(c.newInstance());
            }
         }


//loop to invoke.  
//Loop invoce it in random order.       
            for (int i = 1; i < 9; i++) {
            if (methods[i].isAnnotationPresent(Test.class) && 
               (methods[i].getAnnotation(Test.class).value() < i)) {
                methods[i].invoke(c.newInstance());
            }
        }
    }

但它无法正常工作。

如何使用注释参数优先级进行inove方法?

2 个答案:

答案 0 :(得分:0)

您打算以priority值的相反顺序运行,因此您的循环应该以{{1​​}}从8开始运行。

i

另请注意,条件应检查是否相等for (int i = 8; i > 0; i--) { if (methods[i].isAnnotationPresent(Test.class) && (methods[i].getAnnotation(Test.class).value() == i)) { methods[i].invoke(c.newInstance()); } }

答案 1 :(得分:0)

变化:

for (int i = 1; i < 9; i++) {
    if (methods[i].isAnnotationPresent(Test.class) && 
           (methods[i].getAnnotation(Test.class).value() < i)) {
        methods[i].invoke(c.newInstance());
    }
}

要:

for (int priority = 8; priority> 0; priority--){
    for(Method method : methods){
        if (method.isAnnotationPresent(Test.class) && 
            method.getAnnotation(Test.class).value() == i){
            method.invoke(c.newInstance());
            break; // continue outer loop
        }
    }
}