文件一:
package com.contest;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {  //自定义注解(只能修饰方法)

}文件二:
package com.contest;import java.lang.reflect.Method;public class ApplicationRun { public void run(String className) throws Exception {
Class<?> classType = Class.forName(className);;
Object instance = classType.newInstance();
Method[] methods = classType.getMethods(); // 获得 public 方法。 for (Method method : methods) { // 判断 方法返回类型是 void、方法不接受参数.
if (method.getReturnType() == void.class
&& method.getParameterTypes() == new Class[] {}
&& classType.isAnnotationPresent(Test.class)) {
method.invoke(instance, new Object[] {});
}
}
}
}文件三:
package com.contest;public class RunMethod {
//定义可以用反射放肆调用的方法
@Test
public void show() {
System.out.println("show!");
}
@Test
public void view() {
System.out.println("view!");
}

}文件四:
package com.contest;public class TestContest2 { public static void main(String[] args) {
ApplicationRun applicationRun = new ApplicationRun();
try {
applicationRun.run("com.contest.RunMethod"); //执行
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Done!");
}
}}我的需求是:
当用户将类的全名以字符串的形式传递给该
run 方法时, run 方法会自动执行用户所提供的类中的所有被
@Test 注解所修饰的 public void 且不带参数的方法
  (同时该@Test 注解只能用于修饰方法。)
请问,为什么结果不成功?
没有出现什么问题,也达不到需求,帮看一下哪里的问题!!先谢谢 了

解决方案 »

  1.   

    debug能进invoke那里么。。Class<?> classType = Class.forName(className);
    classType.isAnnotationPresent(Test.class)//这是神马意思?如果指定的注解作用在类上就返回true,但你的是在方法上用Method#getAnnotation
      

  2.   

    嗯嗯,谢谢哦,可是之前在 for 循环里面用 method.isAnnotationPresent(Test.class)) ,是没有生命效果的,所以我才用 “Class” 类里面的 isAnnotationPresent(Test.class)) 方法的,