Erik Kaju
Erik Kaju

Reputation: 3173

Copying class members into other classes - eclipse

A way to move methods to another class

When you need to move some class functionality into another class, it might be easily done by searching for corresponding methods via references of some common variable (Ctrl+Shift+G) and then using Eclipse's refactoring functionality "Move" which allows to move selected methods into some other class.

But it also might happen that you need to copy methods. For instance if you need pretty alike functionality in other class - changing a bit these copied methods is way more comfortable than writing from scratch.

How would/do you act?

PS. Don't think and talk of code duplication issues please, definitely i am not going to have common functionality in two separate methods. Just take it as challenge of copying batch of methods from class A to class B. For whatever reason. And the screenshot is just an illustration of "moving" functionality.

Upvotes: 3

Views: 1330

Answers (2)

mki
mki

Reputation: 635

  • Select one or several methods in the Outline view and copy them (it copies the entire method).
  • Open other class where you want methods to get copied. Navigate to outline view and right-click on class name -> paste. Methods' bodies get successfully copied into another class.

Upvotes: 3

harsh
harsh

Reputation: 7692

Ideally you should refactor original method, write more method(s) to move common functionality which can be used without any change. Use these common method(s) at place from where you are coping and place where you want to paste.

This way your application will have good code re-usability and you don't also have to repeat writing unit tests of common functionality (if that is one of you probable usecase)

Edit: Besides having Alt+Shift+V, Eclipse also has 'Pull Up' and 'Push Down' functionality to cater needs of method reuse in case of hierarchical code structure

Upvotes: 0

Related Questions