日期:2014-05-20  浏览次数:20585 次

为什么调用没有反映?先谢谢了
文件一://自定义注解(只能修饰方法)
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)
------其他解决方案--------------------
引用:
method.getParameterTypes() == new Class[] {}
修改成
method.getParameterTypes().length == 0

 这位大哥,能不能解释一下哈,这个,谢谢。麻烦了。

还有的话,我想纠正的是大哥你在 2 楼回答的应该错了。因为字节码比较只能用 == 号,都是同一个 字节码。
因为上次我听 张孝祥老师的课,他说的:比如 String 和String 的 Class 比较不能用 equals,因为如果用equals 的话无论这样都是true(因为它们都对应同一份字节码),只能用 == 区别 Class 对象(字节码)。