This is an example of how to get and set a bean property. We are using theStatement class.
A Statement object represents a primitive statement in which a single method is applied to a target and a set of arguments. In order to get and set a bean property you should:
- Create a simple class, like
Bean
class in the example. It has two String properties and getters and
setters for the properties.
- Create a new object of
Bean
class.
- Create a new Statement object
for the specified object to invoke the setProperty1
method and by a String array of arguments.
- Call the
execute()
API method of Statement. It finds a method whose name is the same as the methodName
property,
and invokes the method on the Bean object.
- Create a new Expression.
An Expression object represents a primitive expression in which a single method is applied to a target and a set of arguments to return a result. The new Expression is created with the specified value for the specified Bean
object
to invoke the getProperty1
method by the array of arguments.
- Call
execute()
API method of Expression. It finds a method whose name is the same as the methodName
property,
and invokes the method on the Bean
object.
- Call
getValue()
API method of Expression to get the value of the property set in the Expression.
Let’s take a look at the code snippet that follows:
01 |
package com.javacodegeeks.snippets.core; |
03 |
import java.beans.Expression; |
04 |
import java.beans.Statement; |
06 |
public class GetSetBeanProperty
{ |
08 |
public static void main(String[]
args) throws Exception
{ |
10 |
Object
o = new Bean(); |
16 |
stmt
= new Statement(o, "setProperty1" , new Object[]{ "My
Prop Value" }); |
20 |
expr
= new Expression(o, "getProperty1" , new Object[ 0 ]); |
22 |
System.out.println( "Property1
value: " +
(String)expr.getValue()); |
27 |
stmt
= new Statement(o, "setProperty2" , new Object[]{ new Integer( 345 )}); |
31 |
expr
= new Expression(o, "getProperty2" , new Object[ 0 ]); |
33 |
System.out.println( "Property2
value: " +
(Integer)expr.getValue()); |
37 |
public static class Bean
{ |
40 |
private String
property1; |
42 |
private int property2; |
44 |
public String
getProperty1() { |
47 |
public void setProperty1(String
property1) { |
48 |
this .property1
= property1; |
51 |
public int getProperty2()
{ |
54 |
public void setProperty2( int property2)
{ |
55 |
this .property2
= property2; |
Output:
Property1 value: My Prop Value Property2 value: 345
This was an example of how to get and set a bean property in Java.