简体   繁体   中英

Intellij move/refactor private fields and their accessor methods to different class

In my Java project, i have a Java response object which has several private fields and their getters and setters.

public class Response {
        String resp1Id;
        String resp1Message;
        String resp2Id;
        String resp2Message;
        //getters & setters
}

I want to group the members to their own classes and have those objects in my response object like below using Intellij refactoring. The response object is being used in several places, and I cannot refactor it manually. I tried to make it happen using intellj refactor/extract to class but could not do it the way i want to to be. If I use extract-delegate, it comes out differently which I don't want. Any help is appreciated.

public class Response {
        Resp1 resp1;
        Resp2 resp2Id;
        //getters & setters
}
public class Resp1 {
        String resp1Id;
        String resp1Message;
        //getters & setters
}
public class Resp2 {
        String resp2Id;
        String resp2Message;
        //getters & setters
}

I achieved it by following the below steps. There is no single step refactoring tool available in Intellij. [Took clue from Can IntelliJ refactor properties (get/setters) to fields?

1) Make field public in Response.java class.

public String resp1Id;

2) Refactor accessor methods (both getters & setters) using 'inline...' refactoring in intellij. (sample code after this step)

response.resp1Id = "abcdef";
String id = response.resp1Id;

3) Extract field to delegate class New class will be created with fields. (sample code after this step)

public String resp1Id;

4) Refactor - encapsulate fields in new class to make them private and create accessor methods. (sample code after this step)

response.getResp1().setResp1Id("ram");
String kumar = response.getResp1().getResp1Id();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM