2010-08-13 10 views
8

Obecnie używam introspekcji i adnotacji w Javie 1.5. Ma abstrakcyjną klasę rodzica AbstractClass. Dziedziczone klasy mogą mieć atrybuty (typu ChildClass) opatrzone adnotacją niestandardową @ChildAttribute.Nielegalny wyjątek dostępu przy próbie dostępu do adibrogramu z klasy nadrzędnej przez introspekcję

Chciałem napisać ogólną metodę, która wyszczególniłaby wszystkie atrybuty instancji @ChildAttribute.

Oto mój kod do tej pory.

Klasa parent:

public abstract class AbstractClass { 

    /** List child attributes (via introspection) */ 
    public final Collection<ChildrenClass> getChildren() { 

     // Init result 
     ArrayList<ChildrenClass> result = new ArrayList<ChildrenClass>(); 

     // Loop on fields of current instance 
     for (Field field : this.getClass().getDeclaredFields()) { 

      // Is it annotated with @ChildAttribute ? 
      if (field.getAnnotation(ChildAttribute.class) != null) { 
       result.add((ChildClass) field.get(this)); 
      } 

     } // End of loop on fields 

     return result; 
    } 
} 

Implementacja testy, z jakimś dzieckiem atrybuty

public class TestClass extends AbstractClass { 

    @ChildAttribute protected ChildClass child1 = new ChildClass(); 
    @ChildAttribute protected ChildClass child2 = new ChildClass(); 
    @ChildAttribute protected ChildClass child3 = new ChildClass(); 

    protected String another_attribute = "foo"; 

} 

testu sama:

TestClass test = new TestClass(); 
test.getChildren() 

pojawia się następujący błąd:

IllegalAccessException: Class AbstractClass can not access a member of class TestClass with modifiers "protected" 

Uważałem, że dostęp do introspekcji nie obchodził modyfikatorów i mógł czytać/pisać nawet prywatni członkowie. Wydaje się, że tak nie jest.

Jak uzyskać dostęp do wartości tych atrybutów?

Z góry dzięki za pomoc,

Raphael

Odpowiedz

19

Dodaj field.setAccessible (true), zanim pojawi się wartość:

field.setAccessible(true); 
result.add((ChildClass) field.get(this)); 
+0

prędkość światła! Dzięki! –

7

Spróbuj field.setAccessible(true) przed wywołaniem field.get(this). Domyślnie modyfikatory są honorowane, ale można je wyłączyć.

Powiązane problemy