3.15. Converting Constructors to Factory Methods
Problem
You want to convert a constructor to a factory method.
Solution
In Eclipse 3.0, select a constructor declaration or a call to the constructor in the JDT editor, and then select Refactoring→ Introduce Factory.
Tip
This is an Eclipse 3.0-only solution. No equivalent solution exists for versions of Eclipse prior to 3.0.
Discussion
Eclipse 3.0 enables you to convert constructors into factory methods. To do that, you select a constructor declaration or a call to the constructor and then select Refactoring→ Introduce Factory.
For example, say you had this call to a class’s constructor:
public class DisplayApp {
private String text;
public static void main(String[] args) {
DisplayApp DisplayApp = new DisplayApp("Hello");
}
public DisplayApp(String text) {
super( );
this.text = text;
}
}
Selecting the constructor call and then selecting
Refactoring→ Introduce Factory opens the Introduce Factory
dialog. Here, Eclipse 3.0 will suggest the factory name
createDisplayApp
. Click OK to accept that name.
Eclipse then creates that new factory method, replaces the call to
the constructor with a call to that method, and makes the original
constructor private:
public class DisplayApp { private String text; public static void main(String[] args) { DisplayApp DisplayApp = createDisplayApp("Hello"); } public static DisplayApp createDisplayApp(java.lang.String text) { return new DisplayApp(text); } /** * @param text */ private DisplayApp(String text) {
Get Eclipse Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.