How to fix IntelliJ IDEA method parameter auto-completion? - java

I am using IntelliJ IDEA 15, and I noticed that (by default) Eclipse offers a much more convenient auto-completion, when it comes to writing method calls, which require multiple parameters.
Eclipse automatically fills in default parameters and allows you to quickly navigate through them by pressing Tab:
However, IntelliJ IDEA does not handle it as conveniently and makes you write them manually:
Is there a way to make IntelliJ IDEA, handle method call auto-completion in a similar way to Eclipse's, and pre-write all the parameters for you, having you just press Tab (or another key) to navigate through them? If it is not possible in original IntelliJ, is there an add-on/plugin/external tool that will improve the intelligent code completion in such cases?
Note: I am not being lazy, it just gets quite annoying, having to manually complete each parameter and put a comma after each one, when code completion should do it for you.

IntelliJ doesn't do it and AFAIK there isn't a plugin for it.
There is no solution for you (unless you built a plugin yourself, but then you'd just have another job to maintain that plugin)
The alternative is to break the habit/need for it and use IntelliJ's Code Completion shortcuts:
Ctrl+P to view possible parameters for function.
Ctrl+Shift+Space to list the possible variables that could be entered as a parameter in the respective parameter position (based on type).
This also enters a comma if another parameter is required for the function.
Hardcoding numbers/strings as parameters to a custom function wouldn't be advisable as that negates the point of the parameters. It's better practice and more common to pass in a pre-defined variable; At which point Ctrl+Shift+Space is the easiest way for Code Completion.
This would also prevent you from closing quotations and adding commas.
Also note: IntelliSense is Microsoft's Intelligent Code Completion implementation which neither IntelliJ nor Eclipse uses.
As frant.hartm states in their answer:
Unfortunately the view of Intellij developers is that this feature would be too error prone. See this issue on youtrack.
They even state that people are welcome to make a plugin that does this.

The closest thing to this AFAIK is "method parameter completion", which allows you to auto complete parameters of current method as parameters of the inner method call at once (works for methods and constructors when calling super()).
Unfortunately the view of Intellij developers is that this feature would be too error prone. See this issue on youtrack.

IDEA doesn't fill the arguments automatically. You can use Ctrl+Shift+Space for auto-completion (completion is based on type, not name) or Ctrl+Alt+Space for suggestion. Or Ctrl+P to see what arguments are accepted.

Try
Ctrl + Space
for
Basic Code Completion
And like previously was written
Ctrl + Shift + Space
for
Type Code Completion
or try the second variant TWICE. More about Auto-Completing Code is in here

Related

IntelliJ suppress unused warning for API methods

I recently switched to IntelliJ IDEA from Eclipse and I really like the inspectors and find them marking potential errors with warnings for me really useful. I ran into a problem with them that I am unable to solve:
I have some Java projects that are used as APIs in other project, therefore it contains unused methods, which are marked as such:
Unused warning
How can i suppress this for the API methods? Is there an alternative to #SuppressWarnings("unused"), since this also suppresses warnings about unused warnings inside the method and doesn't make it clear to the reader that this method is designed for API use instead of just not being used in the current project?
#Sebastian's suggestion to have your class implement an interface is probably the best way to solve this issue from a good design standpoint. But when that is impractical, there is an alternative...
The "Unused declaration" inspection allows you to configure "entry points" (i.e. a public external API) to ignore. As part of that you can configure "annotations". Anything annotated with the configured annotation is seen as an entry point.
Just configure the inspection to use an annotation that you annotate your public API methods with, either one from a library -- such as #API Guardian (used by some open source projects such as JUnit 5) -- or one you create. Using a library will of course make things easier and consistent across projects. In the below example I used a #PublicApi annotation I created. Notice the method is not highlighted as unused. But the foo String still is highlighted as unused, which is what you want:
As an alternative to opening the Settings dialog, and to limit the impact on your programming flow, you can also use a Quick Fix Intention to add the desired annotation to the "Unused Declaration" settings. After annotating with the desired annotation, place your cursor on the highlighted unused method (or class) name, and invoke the "intention actions and quick-fixes" popup via Alt+Enter or ⌘↩ (or by clicking on the light bulb icon ) and select "Suppress for methods annotated by '{annotation}':
Write an interface for your class. Methods that implement an interface method are not marked as unused. instead the unused methods from the interface are marked as unused but here you can safely use #SuppressWarnings("unused") because you do not have a method body. You could even write #SuppressWarnings("unused") above the whole interface.
In short, no and this isn't really anything to do with IntelliJ, Javac the Java compiler will produce these if you ask it to.
If your method needs this annotation, then that will be for the entire method. However if you just wish a field to be annotated, then that is possible:
#SuppressWarnings("unused")
int iii = 0;
In summary, the method annotation will cover the whole method, placing it per field or instruction will cover that single line.
intellij can do this for you.Just hit Alt+Enter on the occurance that gives you the warning. Some suggestions will pop-up one of them being remove field. there will be an arrow field at the end of the suggestion. Using your arrow keys navigate to the option and use the right arrow to bring up another menu. One of the options will be suppress this for method and suppress this for statement etc.
Suppress for statement will cause this :
//noinspection unused
int iii = 0;
However I have to urge you to heed to the warnings being provided by Intellij and not blindly suppress them.

Intellij IDEA doesn't grey out some unused methods

In intellij IDEA, if a method is unused, the method is shown in a gray color. But in some cases, IDEA doesn't grey out the method, but when I check the references of those methods using alt + F7, IDEA says that the method is unused.
Is this a IDEA bug or is there any reason why IDEA wouldn't grey out these specific methods? If it is a bug, is there some workaround to make IDEA identify that method is unused?
Most likely it's not a bug, it's a limitation for performance reasons. Methods likely to take a long time when searching for usages are skipped.
A workaround is to run Unused Declaration inspection explicitly in all your project via Analyze | Inspect Code or Analyze | Run Inspection by Name. That'll take some time. You can also set up TeamCity server to do it for you automatically every night.
I used to have it working like charm, but one time, I by mistake clicked on alt+Enter on an unused method, and chose to suppress the inspection on unused code. Ever since then, I stopped getting the grayed out methods and code, so since there is a way to get it undone, there sure must be a way to get it back working.
After 5 minutes of searching, I found a solution:
Settings --> Editor --> Inspections --> Java --> Declaration Redundancy --> Unused Declaration
Make sure you check "Unused Declaration"
And I just checked by creating a new useless method, working like a charm.
My answer is quite late, but perhaps it will help others to identify their problem:
IntelliJ didn't mark methods as unused for me, because they were overloaded methods, for example:
1: methodName(String argument)
2: methodName(ArrayList<String> argument)
The first method was no longer used, but the second method was. IntelliJ (I assume) simply checks the method names, and sees that the method name is used, even though one of them is no longer used.
I have checked the other answers on this page for finding unused methods, but have not found a solution to filter out unused, overloaded methods.
It might be a bug if you're using a method with a very common name.
If you tried #Peter Gromov method above, and your method is still yellow, it might be the case that this is a bug.
I had a very common named method, named "stop".
Looking for usages (using ALT + F7) didn't show anything.
Analyzing the whole project, clearly showed that this method did not have any use.
Despite that, the method was still yellow.
I was surprised to find out, that if I try to refactor the method name, I get a pop-up warning that this will change in other places as well.
Turns out, that the refactoring warned about changing the method name in TODO comments. Somehow Lint recognized the TODO comments as using this method.
My advice is to just not name your methods as something that may be written in a TODO comment.
See this image, where I am using a method named "stop" :

How to find and remove all occurances of a function in a class in Eclipse?

I've been rewriting a code base and I've been trying to workout where in Eclipse I can remove all occurrence of a function and any argument/param it may have.
I'm not after clever regex solutions or anything like that, I'm sure the functionality would be in Eclipse, just not sure where ?:)
Many thanks
Just to clarify:
Here's an example...
The function's class myFoo no longer exists. Because it has been refactored incorrectly before arriving with me. Thus I want to search the code base (via an eclipse tool) and remove any line that uses the foo(String string) method from the myFoo class.
Hilight the object (method or variable), then select menu "Search/Refrences" or "Search/Declarations". Do the changes manually, one at a time, so you can review each change. I would never make widespread code changes with a script due to the high probability of unintended consequences.
I'd use replace from the edit menu with
replace='function name' to '// TODO:'
This would highlight them on the gutter. Select that line and press Ctrl + D to delete that line.
It may be an option to remove the body of the function itself and then inline it via Refactor->Inline?
If needed you can of course save the function's code and insert it again afterwards.
I don't know of such a functionality within the JDT. But here is an automated solution you could use:
With MoDisco you can create a model of your java projects. Then you can use an ATL refining transformation to remove all invocations of that method in that model. You can even replace the invocation with some other expressions, if you want to replace the functionality.
If your codebase is large enough than its probably a good idea to have a closer look at these eclipse projects.
Just type a 'MUST_BE_DELETED' or something similar at the beginning/middle/end of the method name (don't use the rename function) then eclipse will highlight all the places that call it in the problems window. When you've fixed all the problems you can go and delete the method.
If you have code in jsp pages then you'll have to manually search for those.
That's what I used to do:
put your cursor at the method name, and press Control+Shift+g (in Windows), or you can do Search -> Reference -> Workspace.
This will search all reference to this method, in the workspace, and remove the reference manually
(Copied from my comment)
If you insist to have the "Remove" done automatically, there is another workaround (may not always works, depends on situation):
make your method body empty,
and then use Refactor -> Inline (you can even choose to delete method declaration)
But I believe there are some cases that this approach is not working. Worth a try to see if it works for your case anyway
Use ctrl+F short cut to open find/replace dialog.Than write your method name in space front of "Find" textbox .Do not write anything in "Replace With" textbox.
Then press "Replace All" button.
This is the most shortcut method.
enjoy :)

Is it possible to prevent a class from using a method in java?

Suppose I have a class called Foo. This class will be modified by many people, and WILL print information to the console. To this effect, we have the following method:
private void print(String message){ ... }
which prints out to the screen in the format we want.
However, while reviewing code from other devs I see that they constantly call System.out.println(...)
instead, which results in barely-readable printouts.
My question is the following: is it possible to prevent any and every use of System.out.println() in Foo.java? If so, how?
I've tried looking this up, but all I found had to do with inheritance, which is not related to my question.
Thanks a lot!
N.S.
EDIT: I know that whatever I have to do to prevent the use of a method could be removed by a dev, but we have as a policy never to remove code marked //IMPORTANT so it could still be used as a deterrent.
EDIT2: I know I can simply tell the devs not to do it or use code reviews to filter the "errors" out but 1) I'm already doing it and it costs a lot of time and 2) the question is whether this is possible or not, NOT how to deal with my devs.
public methods are just that - public. There is no way to restrict access to them.
This kind of problem is usually "solved" by setting up some code-checker like PMD or checkstyle and integrating them into the continuous integration build. So violations of these stuff will be emailed to someone with a big hammer :-)
Although communicating that developers should not use System.out directly would be preferred, you could set System.out to another PrintStream, then use the alternative PrintStream in the private method. That way, when people use System.out.println they won't output anything but you'll still be able to use the alternative PrintStream... something like they do here: http://halyph.blogspot.com/2011/07/how-to-disable-systemout.html
Pre-commit hooks for your revision control system (SVN, Git, Mercurial) can grep for uses of System.{err,out} and prevent commit if they occur.
http://stuporglue.org/svn-pre-commit-hook-which-can-syntax-check-all-files/ is an example that takes an action for different changed files based on file extension for SVN. You should be able to modify that example to take an example based on some subset of Java files and reject if something like the following is true
egrep -q '\bSystem\.(err|out)\b'
You can redirect System.out calls to a streams that ignores the output or that redirects it to your logging system.
System.setOut(printStream);
You can also kill those using System.out.println in a production environment.
You can replace the OutputStream of System with your own implementation that would either throw an exception, or redirect the call to your own print implementation (which you would need to make public).
No, it's not possible to 100% prevent a class from ever using a specific method in Java.
Having that said...
My suggestion would be to add code analysis to your build process and failing the build on any occurrence of System.out.println. A good place to start if you're interested in going this route would be to check out PMD.
Also... have some constructive discussions with your developers and talk about why they're doing what they're doing. Good luck.

How to find static method calls in large Java project?

I'm refactoring some Java code to be more decoupled by changing some static method calls to non-static calls, for example:
// Before:
DAO.doSomething(dataSource, arg1, ..., argN)
// After:
dao.doSomething(arg1, ..., argN)
My problem is that in a large project, it can be hard to find where static method calls are being made. Is there an easy way to do this, either from the command line or in Eclipse?
Such a tool would need to let me ignore "benign" static method calls such as these (either by not finding them in the first place, or by allowing them to be easily deleted from the search results):
String.valueOf(...)
Integer.parseInt(...)
MyClass.someBenignStaticMethod(...)
Some clarifications:
I'm not interested in finding method calls made via reflection
I don't know what static methods currently exist in this project, so it's not as simple as searching for their callers using Eclipse's "Open Call Hierarchy" command (Ctrl-Alt-H), although an easy way to search for non-private static methods would let me use this approach
I'm also interested in finding calls to static methods located outside my project, e.g. javax.mail.Transport#send
I'm looking for a free (as in beer) solution
Do you really need to search? Why not comment out the static method calls one by one? When you compile it then it will flush out the references.
I'd use grep (-R on Linux) to search for initial caps-dot-camel case-open (I don't use it enough to give you the full command line). And then grep -v to get rid of some of the rubbish.
Well, really what I'd do is refactor incrementally. Changes a method, and see what breaks (if nothing breaks, delete the code).
Theoretically you could search through the class files looking for invokestatic. The FindBugs infrastructure would probably help out here (there may be better starting points).
Some IDEs provide support for refactoring. You can refactor every static method one-by-one.
In Eclipse, you can view the call hierarchy to see all the callers of such method. To view the call hierarchy you can select the method name and press Command-Alt-H, or Right-Click on symbol and choose 'Open Call Hierarchy).
We have a product called nWire for Java which might just help. nWire analyzes your code and builds a database of your code components and associations. You can see a brief demo on our web site.
We plan to have reporting capabilities added in the future. In the mean while, if you have some basic experience with databases, you can tap into the nWire repository and, with a simple SQL query, get a list of all your static methods (you can also see the invocations there). nWire uses the H2 database engine which is open-source and free.
I can assist in accessing the database. Drop me a line to support [at] nwiresoftware.com.
I've written a small Java program that uses the excellent ASM library. It lets you exclude packages like java.lang, and produces output that looks like this:
+ java
+ io
- File
# createTempFile(java.lang.String, java.lang.String)
+ javax
+ imageio
- ImageIO
# read(java.io.InputStream)
# write(java.awt.image.RenderedImage, java.lang.String, java.io.File)
+ mail
- Transport
# send(javax.mail.Message)
+ internet
- InternetAddress
# parse(java.lang.String, boolean)
+ xml
+ parsers
- DocumentBuilderFactory
# newInstance()
I'd prefer something that's more easily built into my existing build process, which uses CheckStyle, but this is the best solution I've come up with so far.
A possible solution could be a custom CheckSyle or PMD or ... warning. Currently I have the same challenge and trying it with CheckStyle. It seems to be right easy to write such an extention.

Categories

Resources