Eclipse `sysout` snippet/expansion to System.out.printf? - java

I would like to configure my Eclipse preferences to allow me to type:
printf<CTRL+SPACE> (or ALT+/, or anything I use as a "Content Assist" sequence)
and get this:
System.out.printf("<BANANA>%n", <argument1>);
with the ability to TAB-jump between <BANANA> and <argument1>.
The last part is important, the TAB-jump/replace. Notice the selected text would not include the %n constant, that stays.
I guess to know this I would need to know how to specify snippets, how to use the built-in variables and convert that into an entry in an .epf file.
Also, Eclipse seems to be wicked smart in figuring out from the surrounding context which variable I may want in a certain place. Probably from the type, the line proximity, whatever. Do I have any control on that myself when defining a snippet? Example:
System.out.printf("<BANANA>%n", <argument1>);
// Make BANANA equal to the second public static final String from the top + " split"
// Make argument1 the closest Float in the current block or any other Double, anywhere

I needed something "like" this in an .epf file:
/instance/org.eclipse.jdt.ui/org.eclipse.jdt.ui.text.custom_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="java" deleted\="false" description\="System.out.printf" enabled\="true" name\="pf">System.out.printf("${Message}%n", ${argument1\:var}${cursor});</template></templates>
Cursor after first argument to easily add the eventual argument2, ...
What's missing is a way to specify choice among a set, e.g. "choose one of %s, %d, %f, ..."

Related

How to stop Eclipse from indenting extra spaces in this specific scenario?

When I am writing anonymous classes, I want my anonymous class to look like:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
}
But when I hit enter after line 1, Eclipse will automatically position my cursor at | on line 2:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
| // line 2
some implementation
And when I backspace my way to the front and write {, Eclipse will reposition this { to:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
How can I set my own indentation preferences (for this specific scenario only)?
edit: I have my anonymous class set to next line. It's probably a wrapping issue.
edit2: I give up. I'll just use java conventions of { on the same line as the anonymous class declaration...
edit3: after hunting around the Preference window, toggling without much effect + seeing how Format produces the right output whereas the problem described still persists -- I'd agree that this is probably a bug and I will file a report when I have time.
Go into your preferences. (Window -> Preferences, probably; on mac it'll be under the leftmost menu option ('Eclipse')) - in the filter type 'formatter' to find the entry Java > Code Style > Formatter.
The behaviour you are witnessing is non-standard so you must already have a format defined; you picked this indent behavior, or somebody did who set this as default formatter.
edit this format. Alternatively, check if your project has a custom formatting rule in which case, this same answer applies, but instead go via your project's properties and update the formatting rules there.
The specific rule you are looking for is Brace positions, Anonymous class declaration. You have this set to Next line indented. Set it to something else. It sounds like you want Next line (not indented).

Is there a way to refactor by adding an outer method call using Intellij?

I have this:
Arrays.asList(from(A, 14), from(A, 21), ...
What I need is:
Arrays.asList(of(from(A, 14), 1), of(from(A, 21), 2), ...
The call from(A, number) should be turned into of(from(A, number), anotherNumber).
In other words: I have to update a lengthy list of such from() calls by enclosing them within an of() and adding a second parameter. Ideally, that second parameter would simply count upwards.
Is there a way to that with IntelliJ refactoring tools?
( instead of doing it all manually )
And note: I am not asking for a tools recommendation. I am asking whether a known tool supports a specific refactoring situation.
You can highlight from( and use the "select next occurrence" hot key. Once you have selected all occurrences just replace it with of(from. Once you are done adding of you can use the "alt + left arrow key" to move the cursor to the position where you want to add the number OR use the "select next occurrence" by highlighting the ),.
On Mac the hot key is "CTRL + G" and on Windows\Linux "ALT + J". Here is a list of the hot keys https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf
It is still a bit manual, but beats doing it one by one.
You can try the following:
Extract method with replacing the duplicates for from(A, param)
Inside the extracted method write something like of(from(A, param), NNN)
Inline method
Replace NNN with numbers you need (this has to be performed manually)
If there is some formula that can calculate anotherNumber based on number, you can use it instead of NNN.
"Replace structurally" can do some of what you need.
Select Edit > Find > Replace Structurally...
Enter from($a$, $b$) as the search template
Enter of(from($a$, $b$), i) as the replacement template
Choose Scope: Current File (or Selection, if you prefer)
Hit Find
Hit Replace all
Assuming i is undefined you'll then be left with lots of errors. You can cycle through the errors with F2 and replace the undefined i with the values you want.
Bonus tip: on a Mac, run seq 1 100 | pbcopy at a terminal to put the numbers 1-100 into your clipboard. Then, with multiple cursors in IntelliJ, hit Paste. 1 will be pasted at the first cursor, 2 at the second, etc.

Java Static typing

I am new to learning Java and was explained that every variable needs to be declared. Why do I not need to do this in two steps?
int a = Integer.parseInt(console.readLine("How old are you? "));
console.printf("a: %d", a);
You don't need to declare a variable, but when you do so, you must specify a type (or a super type of what is on the right hand side).
The return value of console.readLine("How old are you? ") is a String and printf can take that as a parameter, so there is no missing type information.
Nothing stops you from writing it in one line, i.e.
console.printf("a: %d", Integer.parseInt(console.readLine("How old are you? ")));
This will work without any problem. Writing it in one line becomes a question of preference / readability and whether you want to do anything with the variable before you print it...
As to your comment, you can check in documentation that console.readLine() returns String.

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.
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
then type .
then <Enter>
then press <ctrl> + <alt> + V
lastly press <Enter> to accept the default name.
Another way besides Introduce Variable is by using their postfix completion feature.
The key thing is to type .var after the expression and then press the tab key.
Eg
myinstance.getMyMethod().var
With your cursor right after .var, press ctrl + space, and then press tab to select the suggestion. You'll then end up with:
IMySomeObject mySomeObject = myinstance.getMySomeObject();
btw, there's many more postfix completions options; I find it to be a very handy feature.

Where does the XXX comment prefix in Eclipse come from?

I was just wandering why is the prefix XXX ?
As far as I know its used for notes/reminders (or at least this is what I use it for and that is what the people on most of the links I googled use it for).
So does anyone know where the XXX prefix come from ?
From Sun/Oracle's Java code conventions, section 10.5.4:
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.
From the Hacker's Dictionary entry for "XXX":
A marker that attention is needed.
Commonly used in program comments to
indicate areas that are kluged up or
need to be. Some hackers liken `XXX'
to the notional heavy-porn movie
rating. Compare FIXME.
XXX, along with FIXME and TODO, is known in Eclipse as a task tag, and is indexed by the IDE to let you find the spots marked with those tags easily. You can edit such tags in the Eclipse Preferences -> Java -> Compiler -> Task Tags.
As to where it comes from: it probably emerged form the "tags" that programmers spontaneously wrote in their code to quickly mark a given line. While FIXME and TODO are explicit enough, the reason XXX was used could be a combination of these reasons:
The string "XXX" does not usually occur in regular source code and is easy to look for with tools such as grep or a simple text search in an editor;
Traditionally, "X marks the spot" which needs attention; triple X even more so;
The X key is very close to the Command/Alt/Windows keys and is easy to reach, being on the lower row of the keyboard.
I can't think of anything else...
Various reasons:
It's easy to search for.
No collision, as no sane person would use it as a variable.
It can used to mark code that needs e*X*tra special attention, dangerous code, not to be seen by underaged, etc.
I've worked with a team where XXX was used to point out a "bug or task that was not yet entered in Trac.". After it was entered in Trac the comment would be changed to TODO with the ID appended.
To Eclipse though, it's just a marker like TODO and FIXME. I imagine that it's originally used as a strong form of TODO. You usually see comments like this:
// TODO: Need to optimize this once n becomes greater than 1000.
But sometimes you'll have a comment like:
// TODO: Fix SQL injection bug before production release!
Unfortunately a quick grep wont make that SQL injection bug stand out among the 1000s of other TODOs. Using XXX here would help mark things that must be done before a milestone/release etc.
There's also a reference to it on Wikipedia:
XXX to warn other programmers of problematic or misguiding code.
It bugs me too, because XXX may also be used for masking input or format numbers,
Thus creating multi markers warning when you describe amount format:
/**
* #param amount (XXX or XXX.XX)
*/
public doSomething(String amount) {
Multiple markers at this line
-XXX or
-XXX.XX)
As #Jean-PhilippePellet suggested, you can remove it from
Preferences -> Java -> Compiler -> Task Tags

Categories