Eclipse – Generate Java toString() method quickly

The Java toString() method us used when we need a string representation of an object. This method is called when we print the object or whenever we treat it like a String. It is defined in Object class and can be overwritten to customize how the object is described.

The default format for an object is constructed by concatenating the Class name, the @ symbol, and a unique hex hash code together. The default hash code method in Object is typically implemented by converting the memory address of the object into an integer.  Therefore, a typical String representation of an object would be: demoObject@112DA82.

This is rarely what you want when getting the object as some String representation for debugging, logging etc. You generally want the variables of the object to be printed with their corresponding values. This can be achieved by overwriting the toString() method in your object.

Example:

class GPSCoordinate {

	private double longitude;
	private double latitude;

 	public ToStringDemo(int longitude, String latitude) {
		this.longitude = longitude;
		this.latitude = latitude;
	}
	public int getLogitude() {
		return longitude;
	}
	public int getLatitude() {
		return latitude;
	}
	// Custom toString() Method.
	public String toString() {
		return "Logitude=" + logitude + "\n" + "Latitude=" + latitude;
	}
}

public class ToStringDemo {

	public static void main(String args[]) {
		GPSCoordinate point = new GPSCoordinate(-33.935,18.424);
		System.out.println(point);
		String s = point + " testing";
		System.out.println(s);
	}
}

When working with larger objects or creating numerous objects at once, it can become tedious to code the toString() method. Thankfully Eclipse has a handy function to auto generate the method for you.
To create the toString method:

  • Right click either on the file, or stand somewhere within the file.
  • Select the Source option
  • Then select Generate toString()… option. This will bring up a screen to ask which variables it should include in the toString() method.
  • When the required variables have been selected simply click on the OK button and it will generate the toString() method.
Tip: Check out other Source options for more auto generation tools like generating Getter and Setter methods.

Eclipse – Mylyn

I was on holiday last week, which gave  me some time to checkout some Eclipse plugins etc. No, I’m not a workaholic. I was just bored. For quite some time now I’ve been hearing more and more about this thing called Mylyn, seeing blog posts, google talks etc. on the subject, but there was always something else that was more interesting to investigate. What a mistake! I’ve been using Mylyn for about 2 days now, and is invaluable. It should be installed by default into Eclipse.

Mylyn is a task management tool that reduces the amount of information you see in the package explorer(navigator) so that only the relevent files to your current task is visible. Generally I find myself frustrated with having numerous projects in my package explorer which I cannot remove as I’m constantly developing on all of them, but rarely have multiple open at the same time. To help organize the package explorer I then create working sets to limit the amount of projects, but even this becomes tedious as I find my self with a huge list of working sets. Another problem I find is that there is no way, at least that I’m aware of, to easily filter packages in a project. Mylyn achieves this with ease.

When using Mylyn you define tasks. A task is simply some work that has to be done. You can give it a title, add some comments, give its a suggested start date and due date so that you can do some project planning etc. No more sticky notes to organize your day, week or even life.

When you want to work on a specific task you activate it. It will then monitor you activity and the files you work on. If you open a file it will be included in the task’s context. Once a file has been opened, it will stay in you context until you explicitly remove it from the context. You can also simply add files to the context without the need of opening them. So far I find including only the files I open works perfectly. Mylyn then limits the package explorer to only show files included in the active task. This significantly reduces the current view by only showing the files and packages that are relevent to your task at hand.

To help you multitask you can easily jump from one task to another, and it will automatically switch context. This included reopening and positioning your cursor where you last where when you had the task activated. This is a significant and invaluable feature. I can now have one task activated with 5 files open, then jump to another task in which case it will close all the current files, save which files where open and where I was in them, load the new task’s context into the package explorer to exactly where I was in it the last time I worked on it. I can then make some changes and jump back to the previous task, in which all the files will be reopened and set to where I just was. And the best thing about this is the task context is not restricted to a single project. Therefore, as you jump between tasks, the relevent projects will all be opened and closed as required. Usually I would need to keep the files I’m working on open so that I don’t lose track of where I was, then open all the projects and files that I need to have open to work on the other task. This leads to a very cluttered package explorer and editor with me having to keep track and not accidentally editing the wrong files.

Mylyn is fairly easy to start using and they have a great getting started guide on their website, and therefore I will not go into any further details. To get started go to: http://www.eclipse.org/mylyn/start/

Try it NOW, with more than a million downloads a month, you won’t be disappointed.

Eclipse – Refactor Method Signature

Refactoring in Eclipse is very powerful. Most developers use refactoring on a daily basis, whether it is to rename packages, classes, method names, or variables. Sadly I find very few developers ever use refactoring to change a method’s signature. This is probably one of the most powerful refactoring tools in Eclipse.

By using the “Change Method Signature” refactoring option, you can change parameter names, parameter types and the order of parameters. It will automatically update all references to the corresponding method. Additionally, parameters and thrown exceptions can be removed or added and method return type and method visibility can be changed.

Typically developers add new parameters to the end of a method. This makes updating the already existing references to the method easier. However, this generally leads to bad method signatures where the parameters that fit together
logically are scattered in no useful order. Although we would like to reorder the parameters to be more logical, it is often a tedious and error prone task to update each existing reference to the method, and therefore it is rather kept as is. Not anymore! By using refactoring you can quickly and easily reorder the parameters and it will update all the existing references automatically. Awesome isn’t it?

To change a method’s signature, simply Right Click->Refactor->Change Method Signature while standing anywhere in the method, or you can even do it while standing on a reference to the method.
Shortcut keys:  ALT+SHIFT+C

Tip: You can keep the existing method signature and mark it as deprecated. This is often useful when it is a API method where the original method signature should still be available.

Eclipse – Export/Import Workspace Preferences

If you use multiple workspaces or use Eclipse on multiple machines you will know how frustrating it is to set up each workspace from scratch.
Things like your custom shortcuts, font settings, perspective layouts etc are all things you would have to set up.

There is a much easier way:

  1. Completely setup your workspace.
  2. Export the preferences of the workspace to file. Select File -> Export -> Preferences. Then select “Export All” and set the output filename. Click Finish.
  3. Now to load your preferences, open the workspace that you want to apply the preferences to. Then select File -> Import -> Preferences. Select the preferences file and click Finish.

That’s it! Very easy and very useful.

Eclipse Custom shortcut keys

Normally I feel that the default shortcut keys of an application should not be changed. A lot of thought and time has gone into assigning the shortcut keys of an application. But… I must admit that I have changed and added some shortcuts to Eclipse which I find are more useful that the originally assigned shortcuts.

To add or change shortcuts open: Windows->Preferences->General->Keys. Here you can find all the Eclipse commands and their associated shortcut keys. I would recommend reading through them just to make you aware of all the commands.

Shortcut key binder

 

A list of my favorite custom shortcuts:

Command Key Binding
Show package explorer Ctrl+p
Generate Getters and Setters Ctrl+g
Team synchronize with Repository Alt+s
Commit changes to Repository Alt+c
Create New Class Ctrl+Shift+N
Export to Runnable JAR Ctrl+j

Note: Some of these key bindings do overwrite existing shortcuts. It is up to you whether or not they are more useful that the original key bindings.

Tip: If working with multiple workspaces or on different machines, instead of setting up each from scratch, simply setup one system and export the preferences to file. Then simply import it into your other workspaces.

 

 

Eclipse – Extract code into a method

Quite often when I write code I find myself ending up with very large methods. These methods can generally be broken down into smaller sub methods. Smaller methods are better to test and debug, and greatly improves code re-usability.

Although the large method looked simple and clear when you wrote it, in a month or less, you  might find yourself struggling to change and update the method. Mostly because it is hard to figure out how even a small change will affect the rest of the method . I promise you that this will not happen if you break you methods into well-defined smaller methods.

Breaking you methods into smaller methods can take some time, as you have to define new methods, cut, paste and replace code. To speed up the process you can use Eclipse’s build in refactor. Eclipse allows you to select a section of code and then to extract it into a new method. I will automatically create the new method, place the selected code into the new method, and replace the selected code with the new method call. It even adds the method parameters.

Example:

  1. First select the code you want to create a new method for.
  2. Then Right-Click->Refactor->Extract method
  3. The Extract Method window will open. This is where you give the new method a name and select the access modifier.
  4. You can then preview the changes by pressing the Preview button.
  5. To accept the code changes press OK.

 

Eclipse Shortcut Keys

Today I’m just going to list a few of the shortcuts I find invaluable in Eclipse. Hopefully you will too.

Shortcuts:

Ctrl+Shift+L: A list of all the shortcut keys. Great to learn new shortcuts.
Ctrl+O: Outline pop-up. Probably the most useful of all the shortcuts. Shows a pop-up list of all the methods in your current class.
You can start typing the method name and it will sort the results shown.
Ctrl+1: Quick Fix. Quick fix is a very powerful tool. From adding missing imports to changing the order of arguments in if statements. Try this and you won’t be disappointed.
Ctrl+F11: Run current application. No more going for the mouse to click run. Mouse = bad.
Ctrl+Shift+T: This opens a jump to Type window. I’ve recently started using it and it is amazing. Instead of opening the package explorer and searching for the class you want to edit, you can use this shortcut to jump to the class by typing the name of the class. It also displays a list of recently used classes.
Ctrl+Shift+R: This is similar to the jump to Type window, except it can be used on any non Java resource files.
Ctrl+/: Comment the current line. invaluable.
Ctrl+Shift+O: Organize imports. If you need to import a class or package simply use this shortcut. It will import the required package if it can find it uniquely. If it finds more than one match it will simply prompt you to select the correct one. It will also clean the current class by removing unused imports.
Ctrl+l: Jump to line number.
Ctrl+i: Auto indent the highlighted code. This can deliver undesired results depending on you coding style.
Ctrl+space: And the best for last. Auto code completion or code assist. Whenever you start typing you can press this combination to bring up the code assist menu which will contain several options to complete you code. I keep finding myself typing an email or MS Word document pressing this combination and being sadly disappointed. Maybe someday…

It is also good to know that you can set up your own shortcut keys. I will post some of my custom shortcuts soon. If you have any that you find really useful, please let me know.

Follow

Get every new post delivered to your Inbox.