Random value in java depending on field type

Is there a way to get a random value depending on the type of field? The exact scenario is to use reflection to get the declared fields of a class. I want to set fake data to the fields that I have.

Field fieldset[] = cls.getDeclaredFields();

for the fld field in the field list, I can get the type using fld.getType() but I have to set a random value depending on the type at runtime

Random rand = new Random();

random.nextInt()gives me an integer ... but all I want is if there is any method or method like rand(fldtype)that should give me a random field type value

+3
source share
3 answers

, . / .

.

0

0 ( ) -1 .

.

Field fieldset[] = cls.getDeclaredFields();
int noOfFiledsLessOne=fieldset.length-1;

Random rand=new Random()

Integer i=rand.float()*noOfFiledsLessOne;

Field randField=fieldset[i];
0

Is that about what you need? Class<?>is the return typeField.getType()

private static final List<Class<?>> seeds = new ArrayList<Class<?>>();

public static int rand(Class<?> clazz) {
  int seed = seeds.indexOf(clazz);
  if(seed == -1) {
    seeds.add(clazz);
    seed = seeds.size() - 1;
  }

  Random random = new Random(seed);
  return random.nextInt();
}
0
source

Source: https://habr.com/ru/post/1793513/


All Articles