Search code examples
javaintellij-ideakeyboard-shortcutshotkeys

Automatically generating of type and reference to returned object for method using hot keys in Intellij IDEA


How can I get the type automatically of returned object for method using hotkeys in Intellij IDEA?

Quite often there are times when you need to modify such line:

myinstance.getMyMethod();

in the following:

IMySomeObject mysomeobject = myinstance.getMySomeObject();

I wish that IDEA did it itself for me to save time. I do not wish to explore method's signature, find its returned type and manually create this reference with a specific type of returned object. It's not convenient.


Solution

  • Using the Introduce Variable refactor.

    Select

    myinstance.getMyMethod(); 
    

    press <ctrl>+<alt> + V and you will see a selections of names to give it like

    IMySomeObject mySomeObject = myinstance.getMySomeObject();
    

    I then select <Enter> as the first option is usually fine.

    I suggest you have a look at all the refactoring tools in the Refactor Menu and learn what they all do.


    You can type m

    enter image description here

    then type .

    enter image description here

    then <Enter>

    enter image description here

    then press <ctrl> + <alt> + V

    enter image description here

    lastly press <Enter> to accept the default name.