Eclipse import shortcut does not work as expected [duplicate] - java

Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:
assertEquals(expectedValue, actualValue);
hit Ctrl + Shift + O and have Eclipse add:
import static org.junit.Assert.assertEquals;
Maybe I'm asking too much.

I'm using Eclipse Europa, which also has the Favorite preference section:
Window > Preferences > Java > Editor > Content Assist > Favorites
In mine, I have the following entries (when adding, use "New Type" and omit the .*):
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
All but the third of those are static imports. By having those as favorites, if I type "assertT" and hit Ctrl+Space, Eclipse offers up assertThat as a suggestion, and if I pick it, it will add the proper static import to the file.

If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.

Eclipse 3.4 has a Favourites section under Window->Preferences->Java->Editor->Content Assist
If you use org.junit.Assert a lot, you might find some value to adding it there.

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for Use static imports (only 1.5 or higher).
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

From Content assist for static imports
To get content assist proposals for static members configure your list of favorite static members on the Opens the Favorites preference page Java > Editor > Content Assist > Favorites preference page.
For example, if you have added java.util.Arrays.* or org.junit.Assert.* to this list, then all static methods of this type matching the completion prefix will be added to the proposals list.
Open Window » Preferences » Java » Editor » Content Assist » Favorites

For SpringFramework Tests, I would recommend to add the below as well
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
org.springframework.test.web.servlet.request.MockMvcResponseBuilders
org.springframework.test.web.servlet.result.MockMvcResultHandlers
org.springframework.test.web.servlet.result.MockMvcResultMatchers
org.springframework.test.web.servlet.setup.MockMvcBuilders
org.mockito.Mockito
When you add above as new Type it automatically add .* to the package.

Shortcut for static import:
CTRL + SHIFT + M

Select the constant, type
Ctrl + 1 (quick fix)
Select "Convert to static import." from the drop down.
"Quick fix" has options even though it is not an error.

In Eclipse 4.9, you can static import existing invocations using a quick fix.
A new quick fix has been implemented that allows the user to convert static field accesses and static methods to use a static import. It's also possible to replace all occurrences at the same time.
More details here

Related

Automatically replacing with var using IntelliJ

I'm migrating some pre Java 10 code and I'm wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it's possible.
The code is full of stuff like:
String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);
And I would prefer:
var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);
I already looked in IntelliJ's settings (Code Style/Inspections) and couldn't find anything.
Go to File | Settings, there select Editor | Inspections, then under Java | Java language level migration aids | Java 10.
Right click on Local variable type can be omitted and select Weak Warning or similar.
Move Your cursor onto any of those warnings in Your code (highlighted grey), open quick fix context help (alt+enter), at Replace explicit type with 'var' move to the right and select Fix all 'Local variable type can be omitted' problems in file
Thanks for #olga-klisho for the idea (in comments)
I'm using IntelliJ IDEA 2021.3.2, but don't think the setting is new.
I've been struggling with this one myself.
It seems that the first time to install IntelliJ locally, by default, it will fall back to using traditional defining of variables (i.e. String s = new String();)
How I managed to change it into using var is after I declared something, for example new String(), either I pressed ⌥ Alt/Option+Enter to declare a variable for that declaration or by using ⌘ Command+⇧ Shift+V shortcut (I'm using Mac and classic Intellij key mapping, so YMMV) which activates declaration of a variable, this would show as follows:
As you see, it suggest to hit that key combination shortcut or clicking on the settings button that would open a pop up like this one:
Make sure you have Declare var type selected and you should be good to go.
Use the IntelliJ Edit -> Find -> Replace... option.
Or Ctrl + R

How to show arguments of java function in vim + eclim?

I have configured vim + eclim OK. Now I can use Ctrl+X and Ctrl+U complete functions. But there is no arguments hint. For example,
FileInputStream fins = new FileInputStream(/* what arguments can be used here? eclipse will show those but eclim not */);
how to show arguments hint in vim + eclim?
Resurrecting this old question, since I stumbled on this.
You can use eclim to lookup the java docs of the class and look through the list of constructors that way using the :JavaDocSearch command.
Because the command uses a browser to render the javadocs, you'll need to add to your .vimrc:
let g:EclimBrowser = 'browser-executable-name'
Replacing browser-executable-name with your console-based browser of choice. Example: lynx, links, w3m
Then navigate over FileInputStream with your cursor and run the command :JavaDocSearch and it will pop up the java doc for the class.
Or enter the class name manually: :JavaDocSearch java.io.FileInputStream
You can use the YouCompleteMe (YCM) plugin with options
let g:ycm_add_preview_to_completeopt = 1
let g:ycm_autoclose_preview_window_after_insertion = 1
Note that this does not work for your Constructor invocations. But at least prototypes for method calls will be shown.
Also, if you don't like the auto-popup of YCM, it can be switched off.

How to do code format switching in eclipse?

A)
public class SomeClass
{
private SomeClass()
{
}
public String someMethod()
{
return "";
}
}
B)
public class SomeOtherClass{
private SomeOtherClass(){
}
public String someOtherMethod(){
return "";
}
}
I have joined a new team and will be working on a project which follows the A) convention. However, I have always been the B) java style person and am way more comfortable with B).
1)On the checked out code, is there a way I could convert the java code style in my eclipse to B)
2)And also ensure the project->Team->Synch with Repo ignores this style change when checking for updates ?
3)Before comitting, I want to switch the code back to the commonly followed style and check it in. I synch for changes every morning and commit changes throughout the day.
Is creating a new profile in the preferences->code style->Formatter the only way ? I also looked at http://astyle.sourceforge.net/ but I am somehow confident there is a simpler eclipse solution to this. How could I achieve this in the simplest possible way ?
I am using eclipse kepler
Work flow:
In Windows > Preferences > Java > Editors Save Actions deselect formatting on save.
Check out code.
Clean up your code(Right click on project go to Source > Clean up. Note this works on project level but not on working set, so you have to do it on each and every project) with your Formatter(B) profile enabled.
In Windows > Preferences > Java > Editors Save Actions select formatting on save and start working.
Same as step 1.
Same as 3 but with formatter profile A.
Commit the code.
These steps can be automated with Ant/Maven script(?) or by developing your own eclipse plug-in.
On sync comparator will NOT ignore style change. IMHO there is no escape. Clean up before sync is only the go.
In Git SCM there are some commit and checkout hooks but I haven't explored on this.

No Main class found in NetBeans

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Java equivalent to #region in C#

I want to use regions for code folding in Eclipse; how can that be done in Java?
An example usage in C#:
#region name
//code
#endregion
Jet Brains IDEA has this feature. You can use hotkey surround with for that (ctrl + alt + T). It's just IDEA feature.
Regions there look like this:
//region Description
Some code
//endregion
There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region.
With Android Studio, try this:
//region VARIABLES
private String _sMyVar1;
private String _sMyVar2;
//endregion
Careful : no blank line after //region ...
And you will get:
No equivalent in the language... Based on IDEs...
For example in netbeans:
NetBeans/Creator supports this syntax:
// <editor-fold defaultstate="collapsed" desc="Your Fold Comment">
...
// </editor-fold>
http://forums.java.net/jive/thread.jspa?threadID=1311
Custom code folding feature can be added to eclipse using CoffeeScript code folding plugin.
This is tested to work with eclipse Luna and Juno. Here are the steps
Download the plugin from here
Extract the contents of archive
Copy paste the contents of plugin and features folder to the same named folder inside eclipse installation directory
Restart the eclipse
Navigate Window >Preferences >Java >Editor >Folding >Select folding to use: Coffee Bytes Java >General tab >Tick checkboxes in front of User Defined Fold
Create new region as shown:
Restart the Eclipse.
Try out if folding works with comments prefixed with specified starting and ending identifiers
You can download archive and find steps at this Blog also.
For Eclipse IDE the Coffee-Bytes plugin can do it, download link is here.
EDIT:
Latest information about Coffee-Bytes is here.
This is more of an IDE feature than a language feature. Netbeans allows you to define your own folding definitions using the following definition:
// <editor-fold defaultstate="collapsed" desc="user-description">
...any code...
// </editor-fold>
As noted in the article, this may be supported by other editors too, but there are no guarantees.
the fastest way in Android Studio (or IntelliJ IDEA)
highlight the code you want to surround it
press ctrl + alt + t
press c ==> then enter the description
enjoy
AndroidStudio region
Create region
First, find (and define short cut if need) for Surround With menu
Then, select the code, press Ctrl+Alt+Semicolon -> choose region..endregion...
Go to region
First, find Custom Folding short cut
Second, from anywhere in your code, press Ctrl+Alt+Period('>' on keyboard)
Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.
I were coming from C# to java and had the same problem and the best and exact alternative for region is something like below (working in Android Studio, dont know about intelliJ):
//region [Description]
int a;
int b;
int c;
//endregion
the shortcut is like below:
1- select the code
2- press ctrl + alt + t
3- press c and write your description
The best way
//region DESCRIPTION_REGION
int x = 22;
// Comments
String s = "SomeString";
//endregion;
Tip: Put ";" at the end of the "endregion"
If anyone is interested, in Eclipse you can collapse all your methods etc in one go, just right click when you'd normally insert a break point, click 'Folding' > 'Collapse all'. It know it's not an answer to the question, but just providing an alternative to quick code folding.
here is an example:
//region regionName
//code
//endregion
100% works in Android studio
#region
// code
#endregion
Really only gets you any benefit in the IDE. With Java, there's no set standard in IDE, so there's really no standard parallel to #region.
I usually need this for commented code so I use curly brackets at start and end of that.
{
// Code
// Code
// Code
// Code
}
It could be used for code snippets but can create problems in some code because it changes the scope of variable.
vscode
I use vscode for java and it works pretty much the same as visual studio except you use comments:
//#region name
//code
//#endregion
Meet custom folding regions ⌥⌘T
Actually johann, the # indicates that it's a preprocessor directive, which basically means it tells the IDE what to do.
In the case of using #region and #endregion in your code, it makes NO difference in the final code whether it's there or not. Can you really call it a language element if using it changes nothing?
Apart from that, java doesn't have preprocessor directives, which means the option of code folding is defined on a per-ide basis, in netbeans for example with a //< code-fold> statement
On Mac and Android Studio follow this sequence:
Highlight the source code to fold
Press Alt+Command+t
Select <editor-fold>
Also you can select other options:
In Visual Studio Code, try this:
//region Variables
// Code you need
//endregion
In Eclipse you can collapse the brackets wrapping variable region block. The closest is to do something like this:
public class counter_class
{
{ // Region
int variable = 0;
}
}
Just intall and enable Coffee-Bytes plugin (Eclipse)
There is some option to achieve the same, Follow the below points.
1) Open Macro explorer:
2) Create new macro:
3) Name it "OutlineRegions" (Or whatever you want)
4) Right Click on the "OutlineRegions" (Showing on Macro Explorer) select the "Edit" option and paste the following VB code into it:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections
Public Module OutlineRegions
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As Stack = New Stack()
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
End If
i += 1
End While
Return lineNumber
End Function
End Module
5) Save the macro and close the editor.
6) Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox (Type: Macro into the text box, it will suggest the macros name, choose yours one.)
7) now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+N.
Use:
return
{
//Properties
//#region
Name:null,
Address:null
//#endregion
}
8) Press the saved shortcut key
See below result:

Categories