2013-10-17 70 views

回答

1

如何

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.reflect.*; 

@Retention(RetentionPolicy.RUNTIME) 
@interface Foo { 

} 

public class X { 

    @Foo 
    public X x = null; 

    public static void main(String [] args) throws Exception { 
     X root = new X(); 
     root.x = new X(); 
     root.x.x = new X(); 

     recurse(root); 
    } 

    private static void recurse(Object root) throws Exception { 
     if (root == null) return; 

     for (Field f : root.getClass().getFields()) 
      if (f.getAnnotation(Foo.class) != null){ 
       System.out.println(root); 
       recurse(f.get(root)); 
      } 
    } 

} 

輸出:

[email protected] 
[email protected] 
[email protected]