Suppose I have a class that has a lot of different fields. This class is a DTO and for testing purposes, I do not care about actual values, just it exists. Is there any tool that can traverse through all fields and set primitives, 0 for Number (0.0 for Float, Double, 0 for Integer, 0L for Long, but not null as default), something like "test" for String?
Also, I want that tool to populate Collections (List, Set, Map).
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
The getDeclaredFields() method of java. lang. Class class is used to get the fields of this class, which are the fields that are private, public, protected or default and its members, but not the inherited ones. The method returns the fields of this class in the form of array of Field objects.
Just a small googling provide this results:
else you can use reflection to populate:
Collection<T>(set,list)
with random size and re-using code to
populate <T>
and so on.
Else XML binding (with jaxb or other technology) can be an option but needs to prepare xml with data in advance.
Except frameworks all other solutions have two big issues: needs to be written and a lot of testing!
If you are using primitives ,they will be automatically set to their default values. In case of Wrapper calss, if you do not care about actual values, you might leave them to null. You can throw a NullPointerException if they are accessed without initializing them.
For populating it in the list, the simplest way should be create a object of class and adding objects to the list.
class DTO
{
int a;
String b;
float c;
DTO (int a,String b,float c)
{
this.a=a;
this.b=b;
this.c=c;
}
public static void main (String args[])
{
List <DTO> list = new ArrayList<DTO>();
DTO o = new DTO (1,"Test",11.3f);
list.add(o);
}
}
Printing the list and overriding toString()
should display the values.
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