Domanda

Is there a fast way to cast an object/primitive to other objects/primitives in eclipse. I am looking for something like a quick try/catch block: You select the block and press Ctrl + Alt + Z to quickly surround the block with a try/catch.

So, for the quick casting you select the block again, you hit the keys and type the name of the object quickly with autocompletion and voila you made the cast.

I know this exists via Ctrl + 1 when an auto-correction is available but I also would like to do it seperately.

Thanks.

È stato utile?

Soluzione

I actually have this code template set up for my Eclipse. Here's how you can configure it.

Open the Preferences dialog by going to Windows > Preferences and then navigate to Java > Editor > Templates. Click on New... here to create a new Code Template as shown below.

Code Template

Now, within the Java file editor, select the Object you want to type cast and hit Ctrl + Space.

Ctrl + Space drop-down

Invoke the code template and you'll get something like

[type] [new_name] = ([type]) new ArrayList<String>();

where the [] indicate that type can be specified using auto-complete.

There's also a default cast template available which can be invoked by typing cast and then hitting Ctrl + Space. The difference is that it doesn't support selections but lets you specify the target object through auto-complete. I find both the variants useful.

[type] [new_name] = ([type]) [name];

Altri suggerimenti

Eclipse provides a way to create shortcuts for quick fixes.

You can create a shortcut that "presses ctrl+1 and then select add cast option". Using this approach, you dont even have to select the block, just step over it, like when using ctrl+1, plus you are using IDE existing option.

It can be done in the menu Window > Preferences > General > Keys and then search for Quick Fix - Add Cast command. Assign your own binding and done! (can't upload image because of my reputation).

PD: In my case, there were two Quick Fix - Add Cast commands and just one of them did the trick, you may have to try both.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top