如何通过java反射为setter方法设置变量
我有一个实体类定义为EmployeeBase.java,它有200个setter方法和200个私有变量 我有一个Employee.java,它扩展了基类EmployeeBase.java,这个基类也只有很少的字段 现在我想为Employee.java中的所有字段创建随机值,并返回Employee对象 我不知道如何设置存在于Employee和基类中的setter的所有值 请帮帮我如何通过java反射为setter方法设置变量,java,Java,我有一个实体类定义为EmployeeBase.java,它有200个setter方法和200个私有变量 我有一个Employee.java,它扩展了基类EmployeeBase.java,这个基类也只有很少的字段 现在我想为Employee.java中的所有字段创建随机值,并返回Employee对象 我不知道如何设置存在于Employee和基类中的setter的所有值 请帮帮我 谢谢。为了减少创建Junit测试的时间和工作量,有一些库,例如和。为了简单起见,我喜欢在测试中使用Podam 将Pod
谢谢。为了减少创建Junit测试的时间和工作量,有一些库,例如和。为了简单起见,我喜欢在测试中使用Podam 将Podam依赖项添加到pom.xml
<dependency>
<groupId>uk.co.jemos.podam</groupId>
<artifactId>podam</artifactId>
<version>7.0.5.RELEASE</version>
</dependency>
2.3。Student.java
使用Podam填充您的豆子:
public class PodamDataGenerator {
public static void main(String[] args) {
PodamFactory podamFactory = new PodamFactoryImpl();
//Limit number of elements to collections fields
podamFactory.getStrategy().setDefaultNumberOfCollectionElements(2);
Student student = podamFactory.manufacturePojo(Student.class);
System.out.println("Podam Pojo\n-----------\n " + student);
}
}
输出
Podam Pojo
-----------
Student[course=Course[code=Dr0zgS5ZKw,name=ZrGJ8xAcJQ],
name=nB6zy558W5,mail=DuW6YyLgo3,phones=[Wlc7axk_A7, nQxDmUlukY]]
希望这有帮助 大多数现代IDE都支持getter和setter生成。另外,一个类中可能不应该有200个变量,通常可以将它们分组到其他类中。我已经有了getter和setter,但我正在寻找具有随机值的对象。我已经生成了getter和setter
public class Student extends Peopple {
private Course course;
public Course getCourse() {return course;}
public void setCourse(Course course) {this.course = course;}
@Override
public String toString() {
return return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
public class PodamDataGenerator {
public static void main(String[] args) {
PodamFactory podamFactory = new PodamFactoryImpl();
//Limit number of elements to collections fields
podamFactory.getStrategy().setDefaultNumberOfCollectionElements(2);
Student student = podamFactory.manufacturePojo(Student.class);
System.out.println("Podam Pojo\n-----------\n " + student);
}
}
Podam Pojo
-----------
Student[course=Course[code=Dr0zgS5ZKw,name=ZrGJ8xAcJQ],
name=nB6zy558W5,mail=DuW6YyLgo3,phones=[Wlc7axk_A7, nQxDmUlukY]]