Java: Accessing Private Members

Using reflection to change the accessibility of a private object field and access it at runtime.

import java.lang.reflect.Field;
 
class Life {
    private int meaning = 42;
}
 
class Hack {
    public static void main(String args[]){
        Life life = new Life();
        try {
            Field field = life.getClass().getDeclaredField("meaning");
            field.setAccessible(true);
            System.out.println(field.get(life));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e){
            e.printStackTrace();
        }
    }
}

Output:

42

  1. Fácil assim?
    Dá pra violar as regras de orientação a objeto dessa maneira?
    É receita garantida? Não tem jeito de evitar?

  2. Sim, metaprogramação em Java, meio burocrática mas bem completa.
    IHMO, eu tenho a tese de que essa coisa toda de privada/protegido não faz muito sentido nem é tem muita utilidade prática, e que na verdade reflete a maneira de pensar corrente (privativo e protecionista) no momento da criação desses conceitos.

  3. Using reflection with arrays and primitive types | JavaHelp.info - pingback on 30 November, 2009 at 5:10 pm

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Trackbacks and Pingbacks: