为什么调用没有反映?先谢谢了
文件一://自定义注解(只能修饰方法)
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 { //自定义注解(只能修饰方法)
}
文件二://通过反射获得“返回类型为 void、接受无参、被 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!");
}
}
文件四://将要执行的类传递到 ApplicationRun 类,让其执行。
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 注解只能用于修饰方法。)
请问,为什么结果不成功?
没有出现什么问题,也达不到需求,帮看一下哪里的问题!!先谢谢 了
[最优解释]
method.getParameterTypes() == new Class[] {}
修改成
method.getParameterTypes().length == 0
[其他解释]
method.getReturnType() == void.class
修改为
method.getReturnType().equals(void.class)
[其他解释]