user1262516
user1262516

Reputation:

Java - accessing public members via reflection

I've read a whole bunch of SO questions, and I can't seem to find the answer.

I have the following class:

public class DatabaseStrings {
    public static final String domain = 
        "CREATE TABLE IF NOT EXISTS domain (" +
            "_id INT UNSIGNED, " +
            "account VARCHAR(20) NOT NULL DEFAULT '', " +
            "domain TINYINT(1) DEFAULT 0, " +
            "domain_string VARCHAR(20) DEFAULT '', " +
            "user_id INT UNSIGNED DEFAULT 0" +
        ");";
}

And elsewhere, I'm trying to access these strings:

for(Field field : DatabaseStrings.class.getDeclaredFields()) {
    field.setAccessible(true); // I don't know if this is necessary, as the members are public

    System.out.println(field.getName());
    System.out.println(field.getType());
    String value = (String) field.get(null); // This line throws an IllegalAccessException inside Eclipse.
    // Do something with value
}

Why do I get an IllegalAccessException? I can see in LogCat the following lines, if I remove the field.get line:

System.out    |    domain
System.out    |    class java.lang.String

References:

Pitfalls in getting member variable values in Java with reflection

Reflection: Constant variables within a class loaded via reflection

Accessing Java static final ivar value through reflection

Upvotes: 1

Views: 726

Answers (1)

user1262516
user1262516

Reputation:

Needed to wrap the .get() in a try-catch block

String value = null;

try {
    value = (String)field.get(null);
    // Do something with value
} catch (IllegalAccessException e) {
    // Handle exception
}

Upvotes: 4

Related Questions