Let's say you have a class: SomeClass with fields a=10, b=20, and c=30, where instanceOfSomeClass.getA()==10. I want a map like this
{
a:10
b:20
c:30
}
I tried this, but got Class can not access a member of class with modifiers "private static final", but I also can't modify this class to not have private static final:
Field[] fields = SomeClass.class.getDeclaredFields();
for (Field f : fields) {
map.put(f.toString(), f.get(instanceOfSomeClass).toString());
}
Any ideas on how to make this hashmap?
CodePudding user response:
When you're looping through the Field objects, use Field.getModifiers() to determine each field's accessibility (public, private, static, etc).
As mentioned in the JavaDoc for Field.getModifiers(), use the class Modifier (which has static methods such as isFinal(), isPrivate(), etc) to "decode" the int value you get from getModifiers().
For example (untested pseudo-code):
for (Field f : fields) {
int modifiers = f.getModifiers();
if (Modifier.isStatic(modifiers)) { // Skip static fields, for example
break;
}
map.put(f.toString(), f.get(instanceOfSomeClass).toString());
}
CodePudding user response:
I guess this is your expected solution:
import java.lang.reflect.*;
import java.util.*;
class SomeClass {
public static int a = 10;
public static int b = 20;
public static int c = 40;
}
class HelloWorld {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
try{
SomeClass sc = new SomeClass();
Field[] fields = SomeClass.class.getDeclaredFields();
for(int i = 0; i < fields.length; i ) {
// Getting the field's name and its value
Object value = fields[i].get(sc);
Object fieldName = fields[i].getName();
// System.out.println("Field = " fields[i].getName() " Value = " value "\n");
// Adding value into the HashMap
map.put(fieldName.toString(), value.toString());
}
} catch (Exception e) {
System.out.println(e.toString());
}
// Iterating through the HashMap
for (Map.Entry<String, String> e : map.entrySet()) {
System.out.println("Key: " e.getKey() " Value: " e.getValue());
}
}
}
Output:
Key: a Value: 10
Key: b Value: 20
Key: c Value: 40
