Velocity Dynamic Property Access
Is it possible to dynamically access properties by using #evaluate? I apologize in advance for the length, but most of this is just example code to fully illustrate my issue.
I have a preferences class which looks like this:
public class DefaultUserPreferences implements Preferences {
//Getters and setters left off for "brevity…"
private Panel defaultPanel;
private OrderByColumn mostActiveSortOrder;
private OrderByColumn recentlyModifiedAccountsSortColumn;
}
Each of these types are simply a custom enum.
public enum OrderByColumn {
NAME,
LAST_ACTIVITY,
GROUP
}
public enum Panel {
MOST_ACTIVE,
RECENTLY_MODIFIED;
public String getCamelCase() {
String[] words = StringUtils.split(this.name(), "_");
String rval = StringUtils.EMPTY;
if (words != null && words.length >= 1) {
rval = StringUtils.lowerCase(words[0]);
for(int i = 1; I < words.length; i++) {
rval += StringUtils.capitalize(words[i].toLowerCase());
}
}
return rval;
}
}
Below is a snippet of how I’d like to display the preferences to the us开发者_运维技巧ers, but I can’t seem to get the getter to be called (I get the following if I evaluate it to get text: test.core.model.entities.DefaultUserPreferences@596fde80.mostActiveSortOrder)
#for ($panel in $Panels)
## The names here are correct
#set($selectName = ${panel.CamelCase}SortColumn)
#set($dynamicProperty = $preferences.$selectName)
<tr>
<td>$panel</td>
<td>
<select name="$selectName">
#for($option in $OrderByColumn)
<option value="$option" #if($option == #evaluate($dynamicProperty) selected="selected" #end>$option</option>
#end
</td>
</tr>
#end
However my getter never seems to be called on the preferences. I’ve added each of the pieces to the Context, and am not having any issues iterating over the Panels, I just can’t seem to get the syntax down to dynamically call the getters on properties. Is this possible in 1.7?
Received this from the mailing list. Basically evaluate only returns a string for display instead of returning a value. Thus the set directive is required inside of the evaluated string.
#set($selectName = "${panel.CamelCase}SortColumn")
#set($dynamicProp = '#set( $selectedPreference = ' + '$preferences.' + $selectName) + ' )')
#evaluate($dynamicProp)
With these lines run, I may then check the value of selectedPreference against the values I am iterating over.
精彩评论