I was looking for some utility class/code that would take a java bean and initialize all its values to random values. It could be done via reflection as some libraries already create the toString() or equals() methods. Is is useful while developing the UI to have some data for example.
Other possible nice to haves:
somebody knows something like this? thanks
EDIT: resolving...Got Apocalisp's sample working and definitively is what I was looking for. It has some drawbacks IMHO:
thanks!
Take a look at Easy Random: https://github.com/j-easy/easy-random.
It allows you to populate a Java Object graph with random data.
Disclaimer: I'm the author of that library
While I did notice that this post may be a bit old, I just happened to have the same necessity, and none of the presented solutions quite seemed to solve it acceptably, so I did some quick-and-dirty fifteen-minute not-quite-generic utility method for generating randomly populated beans, which may or may not be useful for someone else who happens to have a similar problem:
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
import org.springframework.beans.BeanUtils;
public class RandomBeanUtil {
public static <T> Collection<T> generateTestData(Class<T> clazz, int quantity) {
Collection<T> list = new ArrayList<T>();
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz);
Random rand = new Random();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
try {
for (int i = 0; i != quantity; i++) {
T o = clazz.newInstance();
for (PropertyDescriptor descriptor : descriptors) {
Class<?> type = descriptor.getPropertyType();
if (String.class.isAssignableFrom(type)) {
descriptor.getWriteMethod().invoke(o, String.valueOf(new char[]{
(char)('A' + rand.nextInt(26)), (char)('a' + rand.nextInt(26)) }));
} else if (Date.class.isAssignableFrom(type)) {
cal.add(Calendar.DATE, rand.nextInt(60) - 30);
descriptor.getWriteMethod().invoke(o, cal.getTime());
} else if (BigDecimal.class.isAssignableFrom(type)) {
descriptor.getWriteMethod().invoke(o,
new BigDecimal(rand.nextDouble() * 500).setScale(2, RoundingMode.HALF_UP));
}
}
list.add(o);
}
} catch (Exception e) {
// TODO: Improve exception handling
throw new RuntimeException("Error while generating the bean collection", e);
}
return list;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With