开发者

random value in java depending on field type

开发者 https://www.devze.com 2023-02-12 12:07 出处:网络
Is there any way to get random value depending on field type?? The exact scenario is I used reflection to get declared fields of a class. I want to set fake data to the fi开发者_高级运维elds I got.

Is there any way to get random value depending on field type?? The exact scenario is I used reflection to get declared fields of a class. I want to set fake data to the fi开发者_高级运维elds I got.

Field fieldset[] = cls.getDeclaredFields();

for a field fld of fieldlist I can get type using fld.getType() but I have to set random value depending on type during runtime

Random rand = new Random();

random.nextInt() gives me an integer...but all I want is if there is anymetod or way like rand(fldtype) which should give me a random value of field type


You could invoke the method on the random class using reflexion, and have a Map that maps types to functions for the random class. This would allow you to do only one comparison, and add/remove types with less maintenance.

However, you would have difficulty casting the return type in this case.


Generate a random number between 0 to (no of fields) -1 and get the field you need.

Code is something like this.

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

Random rand=new Random()

Integer i=rand.float()*noOfFiledsLessOne;

Field randField=fieldset[i];


Is this roughly what you need? Class<?> is the return type of Field.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

精彩评论

暂无评论...
验证码 换一张
取 消