dhukas
Jul 18th, 2007, 10:01 AM
Hello,
I would like to write some custom property editor (extending PropertyEditorSupport) which transforms between String[] and long in the following way (by example):
{"1", "4"} <-> (long)5 = 101 in binary notation.
The direction from String[] to long can be done in the following way:
public class TestBinding {
public static void main(String[] args) {
test();
}
public static void test() {
Bean bean = new Bean();
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestDataBinder binder = new ServletRequestDataBinder(bean, "command");
binder.registerCustomEditor(Long.TYPE, "bits", new BitBinder());
request.addParameter("bits", "1");
request.addParameter("bits", "4");
request.addParameter("_bits", "1");
binder.bind(request);
System.out.println(bean.getBits()); // 5
}
static class BitBinder extends PropertyEditorSupport {
/**
* @see java.beans.PropertyEditorSupport#setValue(java.lan g.Object)
*/
@Override
public void setValue(Object value) {
if (value instanceof String[]) {
long tmp = 0;
for (String s: ((String[]) value)) {
tmp |= Integer.parseInt(s);
}
super.setValue(Long.valueOf(tmp));
}
}
}
static class Bean {
private long bits;
public long getBits() {
return bits;
}
public void setBits(long bits) {
this.bits = bits;
}
}
}
Unfortunately I'm stuck converting from long to String[] with the very same class (BitBinder) without destroying the working transformation from String[] to long...
Any ideas?
Regards,
Burkhard
I would like to write some custom property editor (extending PropertyEditorSupport) which transforms between String[] and long in the following way (by example):
{"1", "4"} <-> (long)5 = 101 in binary notation.
The direction from String[] to long can be done in the following way:
public class TestBinding {
public static void main(String[] args) {
test();
}
public static void test() {
Bean bean = new Bean();
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestDataBinder binder = new ServletRequestDataBinder(bean, "command");
binder.registerCustomEditor(Long.TYPE, "bits", new BitBinder());
request.addParameter("bits", "1");
request.addParameter("bits", "4");
request.addParameter("_bits", "1");
binder.bind(request);
System.out.println(bean.getBits()); // 5
}
static class BitBinder extends PropertyEditorSupport {
/**
* @see java.beans.PropertyEditorSupport#setValue(java.lan g.Object)
*/
@Override
public void setValue(Object value) {
if (value instanceof String[]) {
long tmp = 0;
for (String s: ((String[]) value)) {
tmp |= Integer.parseInt(s);
}
super.setValue(Long.valueOf(tmp));
}
}
}
static class Bean {
private long bits;
public long getBits() {
return bits;
}
public void setBits(long bits) {
this.bits = bits;
}
}
}
Unfortunately I'm stuck converting from long to String[] with the very same class (BitBinder) without destroying the working transformation from String[] to long...
Any ideas?
Regards,
Burkhard