Java – Create class constructor with fields faster in Eclipse
This post shows how to create a Java class constructor with fields faster in Eclipse. Before the advent of smart IDEs, Java developers write out almost all codes as it was the only way to do and IDEs were in their infancy. Then, fast forward to now! We have Eclipse, and IntelliJ to name a few.
Java Class with many fields
Consider the following Java class with many fields. Although not typical in small applications, such classes do exist, especially in large programs.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
packagecom.turreta.eclipse;
publicclassCrazyHugeJavaBean{
privateStringfield1;
privateStringfield2;
privateStringfield3;
privateStringfield4;
privateStringfield5;
privateStringfield6;
privateStringfield7;
privateStringfield8;
privateStringfield9;
privateStringfield10;
privateStringfield11;
privateStringfield12;
privateStringfield13;
privateStringfield14;
privateStringfield15;
privateStringfield16;
privateStringfield17;
privateStringfield18;
privateStringfield19;
privateStringfield20;
publicStringgetField1(){
returnfield1;
}
publicvoidsetField1(Stringfield1){
this.field1=field1;
}
// ...
publicvoidsetField19(Stringfield19){
this.field19=field19;
}
publicStringgetField20(){
returnfield20;
}
publicvoidsetField20(Stringfield20){
this.field20=field20;
}
}
The Java class has twenty instance variables that we may need to initialize. Back in the day, we would write the getter and settings method one by one. Meanwhile, if we needed a constructor that accepts many fields, we would write out the arguments for the constructor.
Use Eclipse to generate Java class constructors with fields
For this post, we use Eclipse. However, we could use the same principle in IntelliJ or other smart IDEs. First, we need to have Eclipse running and create a Java class with many fields. Then, right-click anywhere in the source code file and choose
Source. Next, choose
Generate Constructor using Fields... option, as shown below.
Then, a window will display from which you can select the fields you wish to include in the constructor.
Finally, click OK. Imagine doing this manually!
Eclipse Creates a Java Constructor
When we go back to our Java class, we can see a new constructor with selected fields.