View Single Post
  #8   Spotlight this post!  
Unread 18-02-2015, 15:35
MatthewC529 MatthewC529 is offline
Lcom/mattc/halp;
AKA: Matthew
FRC #1554 (Oceanside Sailors)
Team Role: Mentor
 
Join Date: Feb 2014
Rookie Year: 2013
Location: New York
Posts: 39
MatthewC529 is on a distinguished road
Re: Get SmartDashboard keys?

Quote:
Originally Posted by Toa Circuit View Post
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);
		}
	}
__________________
Team 1554 -- Oceanside Sailors
  • 2013-2014 - Lead/Sole Programmer
  • 2014-2015 - Lead Programmer, President
  • 2015-? - Team 1554 Mentor
Independent Public Projects

Developer at Legend Zero LLC.
Java/C++ Programmer

Last edited by MatthewC529 : 18-02-2015 at 15:39. Reason: Warning: Reflection is Rarely the Best Option
Reply With Quote