mercredi 4 avril 2018

java reflection - accessing field [duplicate]

This question already has an answer here:

Good day! I want to access field "name" in my Example.class with java reflection

public class Main {
public static void main(String[] args) throws NoSuchFieldException {
    Example ex = new Example();
    try {
        System.out.println(ex.getClass().getDeclaredField("name").get(ex.getClass()));
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

And my Example class for testing reflection

public class Example {
    private String name;

public String getName() {
    return "testString";
}

public void setName(String name) {
    this.name = name;
}

}

Then I have an error

can not access a member of class com.Example with modifiers "private"

What am i doing wrong? Thanks!





Aucun commentaire:

Enregistrer un commentaire