Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将javabean初始化为随机值的方法_Java_Random_Javabeans - Fatal编程技术网

将javabean初始化为随机值的方法

将javabean初始化为随机值的方法,java,random,javabeans,Java,Random,Javabeans,我正在寻找一些实用程序类/代码,它们将获取一个JavaBean并将其所有值初始化为随机值。这可以通过反射完成,因为一些库已经创建了toString()或equals()方法。例如,在开发UI以获取某些数据时,是很有用的 其他可能的好东西: 递归初始化非原语或简单(字符串、日期)成员 初始化bean集合 也许可以给出一些方法来限制生成的值,例如对于我们可以给出范围的数字,对于字符串regexp或通配符 有人知道这样的事吗? 谢谢 编辑:解决…得到Apocalisp的样本工作,并确定是我所寻找的。它

我正在寻找一些实用程序类/代码,它们将获取一个JavaBean并将其所有值初始化为随机值。这可以通过反射完成,因为一些库已经创建了toString()或equals()方法。例如,在开发UI以获取某些数据时,是很有用的

其他可能的好东西:

  • 递归初始化非原语或简单(字符串、日期)成员
  • 初始化bean集合
  • 也许可以给出一些方法来限制生成的值,例如对于我们可以给出范围的数字,对于字符串regexp或通配符
  • 有人知道这样的事吗? 谢谢

    编辑:解决…得到Apocalisp的样本工作,并确定是我所寻找的。它有一些缺点:

    • 这个库的使用范围要大得多,但这对我来说不是问题
    • 除非你花一些时间来研究整件事,否则理解如何为你的对象构建任意的模型是相当复杂的。这是一个缺点
    • 我想它可能更简洁,但这也很好

    谢谢

    我没有为您准备的库,但是如果您有一个随机生成器,那么这个类可能会派上用场:

    public class BeanMethodIterator implements Iterable<Method> {
    
        private static final int MODIFIER_FILTER = (Modifier.PUBLIC | Modifier.STATIC);
        private static final int MODIFIER_EXPECTED = Modifier.PUBLIC;
    
        /**
         * Indicator to filter getter or setter methods. 
         */
        public enum Filter {
    
            /** Only getter methods. */
            GETTERS(new Transform<Method, Boolean>(){
                public Boolean transform(Method input) {
                    return (input.getName().startsWith("get") || 
                            input.getName().startsWith("is")) 
                        &&  input.getParameterTypes().length == 0;
                };
            }),
    
            /** Only setter methods. */
            SETTTERS(new Transform<Method, Boolean>(){
                public Boolean transform(Method input) {
                    return input.getName().startsWith("set") && 
                        input.getParameterTypes().length == 1;
                };
            }),
    
            /** Getter and setter methods. */
            BOTH(new Transform<Method, Boolean>(){
                public Boolean transform(Method input) {
                    return Filter.SETTTERS.condition.transform(input) || 
                        Filter.GETTERS.condition.transform(input);
                };
            });
    
            private Transform<Method, Boolean> condition;
    
            private Filter(Transform<Method, Boolean> condition) {
                this.condition = condition;
            }
    
        };
    
        /**
         * Iterate parent methods also?
         */
        public enum Scope {
            PARENTS_ALSO() {
                @Override
                protected Method[] getMethods(Class<?> c) {
                    return c.getMethods();
                };
            },
            THIS_CLASS_ONLY() {
                @Override
                protected Method[] getMethods(Class<?> c) {
                    return c.getDeclaredMethods();
                }
            };
    
            protected abstract Method[] getMethods(Class<?> c);
        }
    
        private final Filter filter;
        private final Scope scope;
        private final Class<?> theClass;
    
        /**
         * Constructor. 
         *
         * @param theClass
         * @param what
         */
        public BeanMethodIterator(Class<?> theClass, Filter what, Scope scope) {
            this.filter = what;
            this.theClass = theClass;
            this.scope = scope;
        }
    
        /**
         * Constructor. 
         */
        public BeanMethodIterator(Class<?> theClass) {
            this(theClass, Filter.BOTH, Scope.PARENTS_ALSO);
        }
    
        /**
         * Tells if a method is public
         * @param method
         * @return
         */
        private static boolean isPublic(Method method) {
            return (method.getModifiers() & MODIFIER_FILTER) == MODIFIER_EXPECTED; 
        }
    
        /**
         * {@inheritDoc}
         * @see java.lang.Iterable#iterator()
         */
        public Iterator<Method> iterator() {
            final Method[] methods = this.scope.getMethods(this.theClass);        
    
            return new Iterator<Method>() {
                int index = 0;
    
                public boolean hasNext() {
                    while (index < methods.length) {
                        if (isPublic(methods[index]) && filter.condition.transform(methods[index]))
                            return true;
                        index++;
                    }
                    return false;
                }
    
                public Method next() {
                    if (!hasNext())
                        throw new NoSuchElementException();
                    return methods[index++];
                }
    
                public void remove() {
                    throw new UnsupportedOperationException();
                }
    
            };
        }
    
        public static void main(String[] args) {
            for (Method m: new BeanMethodIterator(Date.class, Filter.GETTERS, Scope.THIS_CLASS_ONLY)) {
                System.out.println(m.getName());
            }
        }
    
    }
    
    
    /**
     * Represents a function that takes one input and returns a transformation of that input value i.e.
     * a transformation. The name Transform is used because it is shorter.
     * 
     * @author Hannes de Jager
     * @since 01 Sep 2008
     */
    interface Transform<I, O> {
    
        /**
         * Invokes the function, performing the transformation, to produce an interpreted value.
         * 
         * @param input the input value.
         * @return The computed result.
         */
        public O transform(I input);
    }
    
    公共类beanMethoderator实现了Iterable{
    私有静态最终整型修饰符_FILTER=(MODIFIER.PUBLIC | MODIFIER.static);
    private static final int MODIFIER_EXPECTED=MODIFIER.PUBLIC;
    /**
    *筛选getter或setter方法的指示符。
    */
    公共枚举筛选器{
    /**只有getter方法*/
    GETTERS(新转换(){
    公共布尔变换(方法输入){
    返回(input.getName().startsWith(“get”)||
    input.getName().startsWith(“is”))
    &&input.getParameterTypes().length==0;
    };
    }),
    /**只有setter方法*/
    SETTTERS(新转换(){
    公共布尔变换(方法输入){
    返回input.getName().startsWith(“set”)&&
    input.getParameterTypes().length==1;
    };
    }),
    /**Getter和setter方法*/
    两者(新转换(){
    公共布尔变换(方法输入){
    返回过滤器.SETTTERS.condition.transform(输入)|
    过滤、获取、条件、转换(输入);
    };
    });
    私有化条件;
    专用过滤器(变换条件){
    这个条件=条件;
    }
    };
    /**
    *是否也迭代父方法?
    */
    公共枚举范围{
    家长也(){
    @凌驾
    受保护的方法[]getMethods(c类){
    返回c.getMethods();
    };
    },
    此类仅适用于(){
    @凌驾
    受保护的方法[]getMethods(c类){
    返回c.getDeclaredMethods();
    }
    };
    受保护的抽象方法[]获取方法(c类);
    }
    专用最终过滤器;
    私人最终范围;
    私人期末班;
    /**
    *构造器。
    *
    *@param类
    *@param什么
    */
    公共BeanMethoderator(类、筛选内容、范围){
    this.filter=什么;
    this.theClass=类;
    this.scope=范围;
    }
    /**
    *构造器。
    */
    公共BeanMethoderator(类){
    这(类、筛选器、两者、作用域、父对象和父对象);
    }
    /**
    *告知方法是否为公共方法
    *@param方法
    *@返回
    */
    私有静态布尔值isPublic(方法){
    返回(method.getModifiers()&修饰符过滤器)=预期修饰符;
    }
    /**
    *{@inheritardoc}
    *@see java.lang.Iterable#iterator()
    */
    公共迭代器迭代器(){
    final方法[]methods=this.scope.getMethods(this.theClass);
    返回新的迭代器(){
    int指数=0;
    公共布尔hasNext(){
    while(索引<方法长度){
    if(isPublic(方法[index])和&filter.condition.transform(方法[index]))
    返回true;
    索引++;
    }
    返回false;
    }
    公共方法next(){
    如果(!hasNext())
    抛出新的NoTouchElementException();
    返回方法[index++];
    }
    公共空间删除(){
    抛出新的UnsupportedOperationException();
    }
    };
    }
    公共静态void main(字符串[]args){
    for(方法m:newbeanMethoderator(Date.class、Filter.GETTERS、Scope.THIS_class_ONLY)){
    System.out.println(m.getName());
    }
    }
    }
    /**
    *表示接受一个输入并返回该输入值转换的函数,即。
    *转变。使用名称转换是因为它较短。
    * 
    *@作者Hannes de Jager
    *@自2008年9月1日起
    */
    界面转换{
    /**
    *调用函数,执行转换,以生成解释值。
    * 
    *@param输入输入值。
    *@返回计算结果。
    */
    公共O变换(I输入);
    }
    
    看一看。这是一个高度可配置的框架的一部分,用于生成或多或少的任何类型。提供了基本类型和大多数Java集合类的生成器。您应该能够相当容易地为类创建
    任意
    实例

    编辑以下是示例,已更正:

    import static fj.test.Arbitrary.*;
    import static fj.Function.*;
    
    static final Arbitrary<Person> personArbitrary =
      arbitrary(arbInteger.gen.bind(arbString.gen, arbBoolean.gen,
          curry(new F3<Integer, String, Boolean, Person>() {
            public Person f(final Integer age, final String name, final Boolean male)
              {return new Person(age, name, male);}})));
    

    ApacheCommonsBeanutils()可能对您有用。没有任何现成的实用程序可以使用,但我想所有的构建块都在那里,即访问属性、随机生成器。

    虽然我注意到这篇文章可能是一个
    Person p = personArbitrary.gen.gen(100, Rand.standard);
    
    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;
        }
    
    }