Java, Software Development

Java – Create class constructor with fields faster in Eclipse

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

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.

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.

There are many other similar features Eclipse has. For example, Eclipse can generate hashCode and equals methods. The same goes for other smart IDEs.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like