I have a java class that contains some fields with setters and getters. Something like this:
public class Test{
public String field1;
public String field2;
...
//Setters and Getters
}
I want to do some logic before executing every getter method. In fact I want a method called before calling getter methods, get return value of getter method, modify it and set new value(without changing body of getter methods, if possible using custom annotation). For example:
Test test = new Test();
test.setField1("field1");
test.setField2("field2");
Now, I want when I use test.getField1(), one method called and change the value of filed1 property. Is there anyway for doing that?
Edit: Thanks to Ambrish and Kayaman I realize that one possible way in my spring mvc application is AspectJ. But my question is Is there anyway for doing it with custom annotation?
You can use an AOP library such as AspectJ to define pointcuts for the getter methods. This will allow you to perform things before (and after) calling the method.
You can explore the following options:
AspectJ (Examples)
Reflections (Examples)
If your application is Spring based them first option, AspectJ, is better. Reflection can be used anywhere.
I'm trying to learn how to store objects as XML files in java, but I'm having a bit of a problem.
Most tutorials that I have found have said that I should use the #XmlElement annotation with set methods, however is there another way to use them, as my objects would be easier to make using just the constructors I have for them instead of a set for each field.
The #XmlElement can also be used on the property. You will find more information in the javadoc.
The javadoc gives this example:
public class USPrice {
#XmlElement(name="itemprice")
public java.math.BigDecimal price;
}
All public fields and properties (get/set method pairs) will be treated by default as if they were annotated with #XmlElement. You can add #XmlElement on the get or set method. You can also annotate the field (instance variable). If you do you should annotate your class with #XmlAccesorType(XmlAccessType.FIELD).
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
JAXB does not currently support annotating constructors. If you are dealing with immutable objects then the following may help:
http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html
I would like to copy the property values from Class A to Class B with BeanUtils which has same fields but with different names. Is it possible to provide a map of property name to differentName, age to differentAge etc., and achieve the copying? I am interested to know if this is possible by any means using only Apache Commons utilities (not any other tools).
class ClassA{
private String name;
private Integer age;
... // Setter and Getter methods
}
class ClassB{
private String differentName;
private Integer differentAge;
... // Setter and Getter methods for the private fields
}
Apache Commons BeanUtils has method the method populate(Object bean,
Map properties) accepts a map to populate the Bean with key value pairs.
NOTE: I just saw the limitation on Apache-Commons - but it may still be useful for other people and as far as I am concerned the better solution.
Use Dozer when the names match it will automatically copy the values. Or as in your case you can specify source and target Members in an xml mapping file.
I need to render objects in JSON and send them to the client but I need to exclude fields like email and password for obvious reasons.
I know play uses GSON (by google?) and you can pass a serializer class when calling the renderJSON() method. However I'm rendering different types of classes at once using a container class:
public class JSONContainer {
public List<User> userList;
public List<Toy> toyList;
}
For each class it's possible to make a Serializer class implementing GSON's JsonSerializer<...> method. But if I render a JSONContainer object like this: renderJSON(container) how can I pass the serializer classes to the rendering method?
Or is there maybe an easier/better way to do this?
Take a look at this post, which gives you a couple of options.
It would appear that the best option is to the #Expose (com.google.gson.annotations.Expose) annotation to mark the fields that you want to be serialised by Gson. You then need to use the GsonBuilder to specifically only include the #Expose fields.
Alternatively, as you have mentioned in your post, you can simply build your serialisations yourself. If you look at this post, it shows how specific class types are registered against the GsonBuilder, so any object of that found as part of the serialisation will use your specific serialiser.
can I define setter method to return this rather than void?
Like:
ClassA setItem1() {
return this;
}
ClassA setItem2() {
return this;
}
then I can use new ClassA().setItem1().setItem2()
There is a lot of misunderstanding about JavaBeans spec.
The main reason for it's existence is the unified Java "component" model. It's a way to interact programatically with a Java Object using Reflection. The API itself is named JavaBeans Introspection. Please, take a look at example usages and You will know a lot more than an average Java programmer does.
Introspection API can be used to manipulate GUI elements in an unified manner. Your component exposes it's properties as a pairs of getters and setters so that they could be discovered and manipulated at run-time on a GUI builder's property sheet.
So, mixing fluent APIs and JavaBeans Spec in my opinion is a no-go. That's two completely unrelated concepts and can disrupt each other. JavaBeans Introspection might not work when method signature differs (return type).
Take a look at this example (taken from linked tutorial):
public class SimpleBean
{
private final String name = "SimpleBean";
private int size;
public String getName()
{
return this.name;
}
public int getSize()
{
return this.size;
}
public void setSize( int size )
{
this.size = size;
}
public static void main( String[] args )
throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}
This example creates a non-visual bean and displays following properties derived from the BeanInfo object:
class
name
size
You might want to see what happens when You change void return type to anything else. I have done so and the result is the same. So, does that mean it's allowed?
I'm afraid no. The JavaBeans spec is quite strict about those method signatures. It just happened that implementation is forgiving. Nonetheless, I'd disadvise mixing fluent interface with JavaBeans. You can't really rely that, if the discovery works now, it will also in future.
But, from the other side - it looks like You don't use JavaBeans to full extent. Only the getters/setters pair of method. It's up to You how You implement and design Your APIs.
The JavaBeans Specification describes a JavaBean as:
A Java Bean is a reusable software
component that can be manipulated
visually in a builder tool
They are required to provide introspection, customization, events and persistence among other properties (Section 2.1: What is a bean?)
It is common to call a "Java Bean" to a Plain Old Java Object with accessor methods following the JavaBeans Specification (Section 7.1 and 8.3). The truth is that such object could still be far from being compliant with all the requirements.
If the object your are defining in this class is actually a JavaBean then your method must return void according to JavaBean Specification, section 7.1 where accessor methods are described as follows:
void setFoo(PropertyType value); // simple setter
PropertyType getFoo(); // simple getter
The section 8.3 named designed patterns for properties says:
By default, we use design patterns to locate properties by looking for methods of the form:
public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is<PropertyName>();
However, if your class is just a POJO then there is nothing wrong with using your method chaining strategy because you are allowed to deviate from the specification since you are not actually building a JavaBean. Not all the classes you define are supposed to be JavaBeans after all, right?
Your might like to take a look at the Oracle JavaBeans Tutorial.
No reason you couldn't do that. Personally, if the setters are being used during object creation, I'd name them withItem1() and withItem2().
ClassA obj = new ClassA().withItem1(item1).withItem2(item2);
Makes it a bit clearer (to me anyway) what the intent of the methods are.
After checking the Oracle JavaBean pages I didn't find anything which explicitly tells you that the setters need to be void. Nevertheless all examples have void set-methods.
The PropertyDescriptor in the Java API support non-void setters, so I think it should be pretty safe to let your setters return this. To be on the safe side you should probably check out if the frameworks you intend to use that uses reflection. For instance didn't Spring support non-void setters in xml config prior to version 3.1.
I would guess this is not in violation of the JavaBean specification, although I am not sure of it.
Check out the following example:
public class JavaBean {
private String value;
public String getValue() {
return value;
}
public JavaBean setValue(String value) {
this.value = value;
return this;
}
public static void main(String[] args) throws Exception {
JavaBean bean = new JavaBean();
JavaBean.class.getMethod("setValue", String.class).invoke(bean, "test");
System.out.println(bean.getValue());
}
}
Many frameworks access JavaBeans using the reflection API. As you can see above, accessing a settter which returns 'this' is not influenced by the return type (the return type is not used to locate a method via reflection). It also makes sense, because you cannot have two methods in one scope that are identical except for their return type.
Just to add that for people using Spring 3.1+ this is not an issue anymore
see
http://static.springsource.org/spring/docs/3.1.0.M2/spring-framework-reference/html/new-in-3.1.html
Yes. This is a somewhat common technique called Method Chaining, and can be used to create a "fluent interface".
See: http://en.wikipedia.org/wiki/Method_chaining, http://en.wikipedia.org/wiki/Fluent_interface
Absolutely nothing to stop you doing that but why. If you want to do this create a constructor that takes the args. Bare in mind some software that uses beans would not be expecting return values and may have some unexpected results
If you just want to simplify initialisation, (maybe to set up tests) you could use some groovy code.
There is nothing preventing you from providing setter methods which return the target object as a convention in your interface...
However, you must also use the canonical signature for Java Bean Simple Property setter methods (e.g. void setProp(Type t)) or the bean property will not be recognized as writeable by other software which expects that signature.
The Builder pattern is generally used for constructing immutable objects. Even though JavaBeans by nature aren't immutable, I have frequently used the builder pattern on my JavaBeans because it provides a fluent interface that I can use in my tests. The two are easily compatible with each other without breaking the JavaBean specification. You can check out it out on Stack Overflow at Builder Pattern in Effective Java
You just need to make sure you include a default constructor as well as the private Builder constructor, and then put your standard getters and setters in the JavaBean object.
This is much cleaner than constructor chaining, and easier to read as well.