今天碰到一个问题,由于是菜鸟级别的,都不太明白这段代码什么意思。我不明白为什么只会输出一个值,并且还是Test里面第一个方法,打印的methods的长度竟然是10,太让我迷茫了。。。
package com.weixing.autoproxy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {
public int id() default 5;
public String description();
}
class Test {
@TestAnnotation(id = 6, description = "g")
public void g() {
}
@TestAnnotation(id = 7, description = "i")
protected void i() {
}
@TestAnnotation(id = 8, description = "f")
void f() {
}
@TestAnnotation(id = 9, description = "h")
private void h() {
}
@TestAnnotation(id = 10, description = "j")
private void j() {
}
}
public class Anno {
public static void main(String[] args) {
Method[] methods = Test.class.getMethods();
System.out.println("methods.length:" + methods.length);
for (Method m : methods) {
TestAnnotation a = m.getAnnotation(TestAnnotation.class);
System.out.print(m.getName());
if (a != null)
System.out.print(a.id() + " " + a.annotationType() + " "
+ a.description());
}
}
}
package com.weixing.autoproxy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {
public int id() default 5;
public String description();
}
class Test {
@TestAnnotation(id = 6, description = "g")
public void g() {
}
@TestAnnotation(id = 7, description = "i")
protected void i() {
}
@TestAnnotation(id = 8, description = "f")
void f() {
}
@TestAnnotation(id = 9, description = "h")
private void h() {
}
@TestAnnotation(id = 10, description = "j")
private void j() {
}
}
public class Anno {
public static void main(String[] args) {
Method[] methods = Test.class.getMethods();
System.out.println("methods.length:" + methods.length);
for (Method m : methods) {
TestAnnotation a = m.getAnnotation(TestAnnotation.class);
System.out.print(m.getName());
if (a != null)
System.out.print(a.id() + " " + a.annotationType() + " "
+ a.description());
}
}
}