📄 stringflags.java
字号:
package jodd.util;
import java.util.HashMap;
import java.util.Iterator;
import jodd.bean.BeanUtil;
/**
* Parses string and sets bean boolean parameters (flags) depending on
* exisiting characters. Class may be used when methods has many boolean
* parameters. In this cases, a single string can replace all those
* parameters, where chars represent if some boolean property should be
* set to <code>true</code> or <code>false</code>.
* <p>
*
* Usually, this class is instanced and configured in static block of a
* class that uses it:<br>
* <code>
* private static StringFlags flags = new StringFlags();
* static {
* flags.addFlag('p', "fooP", true);
* flags.addFlag('d', "fooD", false);
* }
* </code>
*
* Flags boolean values are those that properties will be set to if
* coresponding character exist in option string. This means that when such
* character doesn't exist in options string, its parameter will be set to
* inverse value. In above example, if option string contains char 'p' then
* setFooP(true) will be performed, otherwise setFooP(false) will be
* performed. For the 'd' flag is opposite: if it is present in the option
* string, setFooD(false) will be executed, otherwise setFooD(true) will be
* executed.
*/
public class StringFlags {
private HashMap map = new HashMap();
class Flag {
String bpname;
boolean val;
}
/**
* Add new flag to the buffer.
*
* @param c character flag
* @param bpname name of bean property (without set or get)
* @param val value that will be set if character exist in the string.
*/
public void addFlag(char c, String bpname, boolean val) {
Flag f = new Flag();
f.bpname = bpname;
f.val = val;
map.put(new Character(c), f);
}
/**
* Clears complete flags buffer.
*/
public void clearFlags() {
map.clear();
}
/**
* Parses given string and sets the boolean properties of a bean.
*
* @param params option string, contains char flags
* @param o object to populate
*/
public void parse(String params, Object o) {
if (params == null) {
params = "";
}
char[] ca = params.toCharArray();
Iterator i = map.keySet().iterator();
while (i.hasNext()) {
Character c = (Character) i.next();
Flag f = (Flag) map.get(c);
if (f == null) {
continue;
}
boolean b = f.val;
if (params.indexOf(c.charValue()) == -1) {
b = !b;
}
BeanUtil.setProperty(o, f.bpname, new Boolean(b));
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -