Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill all the fields in the class?

Tags:

java

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).

like image 571
Cherry Avatar asked Aug 15 '13 10:08

Cherry


People also ask

How do you get all fields in a class?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do you find the declared field of a class?

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.


2 Answers

Just a small googling provide this results:

  • EasyRandom simple to use modern java solution, formerly known as Random beans
  • EasyRandom for Java 6, formerly known as JPopulator.
  • PODAM with a tutorial

else you can use reflection to populate:

  • primitive/wrapper with default value
  • string with rendom value
  • 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!

like image 51
Luca Basso Ricci Avatar answered Sep 19 '22 22:09

Luca Basso Ricci


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.

like image 30
Malwaregeek Avatar answered Sep 21 '22 22:09

Malwaregeek