Quote:
Originally Posted by Toa Circuit
I should clarify. I need to do it programmatically, in the robot code. (I want to save values to disk so we don't keep losing them) I'd sneak through and grab the underlying hashtable, but it's private in WPILib.
When you do
Code:
SmartDashboard.putString("Key","value");
"Key" is the key. I need to, through code, fetch a list of all keys that are on the SmartDashboard/NetworkTable.
|
If you REALLY needed to, what says you can't get the private hashtable? We have experimented with grabbing underlying NetworkTable object via reflection but generally this has been fruitless for our needs, requiring more clever solutions.
Java's Field object allows you to set the access flag and it isn't like WPI's launch script executes the program with the default SecurityManager. Just remember Reflection is expensive and there is probably a better way as long as you have the time to look for the better way.
To retrieve a Field, convert it to the right type, and to ensure it is returned to it's original accessibility we use:
Code:
private static Object retrieveField(Field field, Object obj) throws IllegalArgumentException, IllegalAccessException {
Object item = null;
final boolean accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(!accessible);
}
item = field.get(obj);
if (!accessible) {
field.setAccessible(accessible);
}
return item;
}
public static <T> T getStaticField(Class<?> klass, String fieldName, Class<T> conversionClass) {
try {
final Field field = klass.getDeclaredField(fieldName);
return conversionClass.cast(retrieveField(field, null));
} catch (final Exception e) {
throw new RobotExecutionException("Failure to reflectively obtain Static Field '" + fieldName + "'!", e);
}
}
public static <T> T getInstanceField(Class<?> instClass, Object instance, String fieldName, Class<T> conversionClass) {
try {
final Field field = instClass.getDeclaredField(fieldName);
return conversionClass.cast(retrieveField(field, instance));
} catch (final Exception e) {
throw new RobotExecutionException("Failure to reflectively obtain Instance Field '" + fieldName + "' from Object '" + instance + "'!", e);
}
}