|
How to get and set the Property of a Bean |
|
|
This Java tip illustrates a method of getting and setting properties of a Bean. This tip
uses expression and statement for setting the properties. Developer may get and set
three types of properties, an Object, a primitive type, and an array. Both these classes
use the name of the method that gets or sets the property.
Object obj = new MyBean();
try {
// Developer may get the value of prop1
Expression expr = new Expression(obj, "getProp1",
new Object[0]);
expr.execute();
String s = (String)expr.getValue();
// Developer may set the value of prop1
Statement stmt = new Statement(obj, "setProp1",
new Object[]{"new string"});
stmt.execute();
// Now developer may get the value of prop2
expr = new Expression(obj, "getProp2", new Object[0]);
expr.execute();
int i = ((Integer)expr.getValue()).intValue();
// Now developer may set the value of prop2
stmt = new Statement(obj, "setProp2",
new Object[]{new Integer(123)});
stmt.execute();
// Further get the value of prop1
expr = new Expression(obj, "getProp3", new Object[0]);
expr.execute();
byte[] bytes = (byte[])expr.getValue();
// Finally setting the value of prop1
stmt = new Statement(obj, "setProp3",
new Object[]{new byte[]{0x12, 0x23}});
stmt.execute();
} catch (Exception e) {
}
public class MyBean {
// Property prop1
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
// Property prop2
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
// Property prop3
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.