Remove redundant casts in Java - java

I've been generifying some Java code that used lots of casts, and now most of them are redundant and unnecessary.
It could be very tedious to inspect all the usages of the code to remove them, so: are there any tools to help to identify (and remove) superfluous casts?

This can be automatically done using Eclipse Helios. In your project, go to Properties -> Java code Style -> Clean Up. There, edit a profile, go to the "Unnecessary Code" Tab and check "Remove unnecessary casts". Then right-click your source root and klick Source-> Clean up. Job done.

If you're using Android Studio it's an easy fix: Analyze > Code Cleanup

In Eclipse, under "warnings and errors" you can set "Unnecessary cast or instanceof operations" to be "Warn" or "Error" rather than "Ignore". That should help you find them very quickly, although it won't clean them up for you.
But you can also set a "Save" action configured with an "Additional action" of "Remove unnecessary casts".
And you can right-click on an area of Package Explorer, select "Clean up..." and configure that with a "Remove unnecessary casts" action.
So basically this should be simple :)

You should probably use a tool to analyze your Java source code for potential problems (such as unnecessary casting).
Perhaps you can try PMD: http://pmd.sourceforge.net

If you use Eclipse, this should be fairly easy. Right click the class/package/project and select Source - Clean Up....

Related

Eclipse errors won't appear or disappear unless project is saved

Errors in my code won't appear until I save the project.
Not even warnings are popping up until I save.
All that it says whenever I type something in is "1 changed line"
For me, the fix was to disable Annotation Processing:
Open project properties
Java Compiler -> Annotation Processing
Disable "Enable annotation processing"
After disabling, warnings and errors are displayed immediatly (if "Build automatically" is checked, as mentioned by #greg-449). Also code completion, refactorings and quick fix etc. are much faster and smoother.
This also removes the .apt_generated folder in the project structure.
I didn't face any problems after disabling it. If you face problems, like Annotations not beeing checked during compilation, you may have to enable annotation processing but specifing the options and provide the source containing the annotation in the "Factory Path" sub-option (Java Compiler > Annotation Processing > Factory Path).

Automatic imports in Eclipse

In Eclipse, I have to press ctrl+space each time I refer to the type of an unimported class. Having to go back and press ctrl+space feels rather unnecessary. Is there a way to make Eclipse behave like IntelliJ in this case? It should not really be hard to know it should import the UserFactory and User class when I say:
User user = UserFactory.makeUser();
I've seen that you can press Ctrl+1 (quick fix) or Ctrl+Shift+O (Organize imports) to solve this problem, but I would like this to go automatically as it does in IntelliJ. Does anyone know a plugin or a setting that enables this type of behavior?
Open Eclipse's preferences and then go to "Java > Editor > Save Actions". There, enable "Organize Imports".
Now, whenever you save your file (yes, in Eclipse you still need to save the file, not as in IntelliJ where this happens automatically), Eclipse will try to figure out if it needs to add imports to compile the code. It will do so whenever the class name is unique. If it is not (e.g. List in java.util and in java.awt), it will not import it.
You can configure the "organise imports" action even more to ignore certain packages (e.g. java.awt if you never to gui-stuff), so you have fewer name-conflicts and more auto-imports. Look at question Exclude packages from Eclipse's organize imports for infos how to do that.
So I noticed that Eclipse had started to seemingly do all the necessary imports completely automatically.
And I started to look for how Eclipse can automatically add imports.
But all I could find was to use the Ctrl+Shift+O shortcut to Organize imports.
And that could probably be quite efficient if you want to do many at a time.
However there are at least two (or maybe three) other methods to invoke this.
Window, preferences, Java, Editor, Save actions. You will need to check: "Perform the selected actions on save" and "Organize imports".
Window, preferences, Java, Editor, Typing: Under "When pasting" you can select "Update imports".
I am not sure if this is a way of it's own or if it is a variant of what happens when pasting. But if you use ctrl + space to help with auto completing what you are writing it will also Organize imports.
So for example if I have no imports in a class and I start typing: JP and then I press ctrl + space to help me complete and I choose JPanel it will apparently automatically add: import javax.swing.JPanel; for me.

Eclipse code completion automatic deactivation

Whenever I run Eclipse, it suddenly deactivates some completions tags (but not all) with no reason. This happens always during, when I write some code. At the start of Eclipse, everything is okay but after a while this problem occurs. Every time I solve this by resetting the preferences and restarting Eclipse. But it takes too much time and annoys me.
Is there a special Hot-Key to (de)activate some completions tags?
I would bet on a plugin malfunction. Try to reinstall Eclipse from scratch without any custom plugins, and add only what you need, then add them one by one until you run into this problem.
Alternatively, open Eclipse->preferences->install/update->unintsall or update (link)->configuration->view error log and see if you get any exceptions on any plugins, if you identify something fishy, uninstall that plugin.
In my case the Eclipse Preferences named Type Filters (under Java | Appearance) seemed to cause that experience. We had excluded all common root package names (com., org., sun.), but also java. and javax.*. After deaktivating those entries in the "Filter list" Eclipse's Ctrl-Space again provides the missed proposals.

IntelliJ. Debug a program even if it does not compile

I have a Java project in IntelliJ that compiles, and now I am slowly changing.
Is there a way to ask IntelliJ to run the project, even if some parts of the code still do not compile? If so, how?
Why I would need this, you ask? see this ticket:
IDEA-61945 Run and Debug commands should ignore compile errors not related to the main being run.
http://youtrack.jetbrains.net/issue/IDEA-61945?query=it#tab=Comments
Please, do not answer this post questioning whether I should or I should not need to run a project even if it does not compile. please.
If not possible in IntelliJ, is it possible in maven? How?
In Intellij 12 you also have the following option (which personally I find the best one):
Go to Edit configuration of your launcher
Go to the before launch section
If 'Make' is in the list: remove it
Add 'Make, no error check'
Now, when you run, a make will still be done automatically but the run will continue even if the are compilation errors.
Regarding the above debate; I think it makes perfect sense to be able to run a part of the code that does compile even if another part of the code does not not; e.g. if that other part of the code belongs to a module that is in your project but not involved when running.
I ran into this exact same problem at work today. Before now, I probably would have been quick to jump on the bandwagon of, "Why would you ever want to do that?" Turns out that Eclipse lets you do exactly this, and if you start working concurrently with other developers who depend on this feature (which is to say, check in code that doesn't compile), it's handy to be able to do the same in IDEA!
And lucky for us IDEA users, you can. Follow these instructions from the FAQ for Eclipse Users, and you're good to go:
To be able to run code with errors, you can select the Eclipse
compiler in Settings dialog, Compiler, Java Compiler and add the
-proceedOnError option to the Additional command line parameters for the compiler.
The only thing that's lame is that it's not quite as seamless as in Eclipse. First, you'll have to untick the option to Make before run because IDEA won't run if make fails. Then, you'll have to remember to build before running. With those caveats, though, you should be able to accomplish what you're after.
Stijn Geukens's answer is correct, but it can be improved.
In Intellij Idea version 12 instead of removing the "Make" rule it can be replaced with "Make, no error check". This way project will be rebuilt (compiler will atempt to do it), but it will run the program independently of compile outcome.
If you want to debug just one part, then you can create a unit test around that. If you do not use the class that does not compile, then you can still debug the unit test related code.
When there are compilation errors, you can exclude specific files from compilation.
Go to the Messages window (if it is not visible: View -> Tool Windows
-> Messages)
Right click the problem file
Exclude from compile
At least in Intellij 12 you can achieve this.
First try to compile the project, including the broken class(es).
Then in the Messages view, containing all the compile errors:
Right-click the class you want to exclude
Click 'exclude from compile'
See this question on how to reinclude afterwards.
For Intellij 2017.3.1 my configuration is like this:
Use the Eclipse Compiler: Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Use compiler: Eclipse
Select "Proceed on errors"
Edit your desired configuration defaults (I use this for JUnit) before launch to Build, no error check: Check this screenshot
Additional step in order for Intellij not to open the classes with errors when you run your configuration. Un-select Automatically show first error in editor in Settings -> Build, Execution, Deployment -> Compiler
PS: This configuration is not perfect for all usages. It only works when you are fixing unit tests that were failing because of your changes in implementation code. When you go back to implementing features it is more useful to disable this feature since it will let you run you implementation code with errors and it will not jump to compilation errors. You need to go back and forth with changing the Eclipse compiler with the Javac one for best results.
Wow, it's been a while since I've been in IntelliJ and I miss it dearly! From my recollection you should be able to right click the main method in a module and run it directly so long as the remainder of the files in the module compile. I don't think it matters that a second module in the same project has errors. Is that not working for you?
updating for version 2017 - 2.5 community as menu options are slightly different
Navigate to:
Run>Edit Configurations
near the bottom of the Run/debug config window look for
"before launch: Activate tool window "
the field below this heading lists your current build config settings.
Use the + and - symbols in order to add and remove build preferences.
Once completed
Select apply then Okay
Thats it!
I don't think its possible at all. How you can run something that doesn't compile? That would be like driving a car that isn't put together. You could comment out the files that don't compile, so that the project compiles....
Edit -- or you can have Intellij not count the file as source by
Right Click on your project -> open module settings -> select your module -> select the file -> excluded

Hints to improve Eclipse performance

Working in Eclipse with big projects can be painful because of IDE works slowly, sometimes stops and doesn't respond. I know it can depends on OS, version of Eclipse etc.
All eclipse developers have tricks which tuning workspace in Eclipse, What should be turn off to improve performance the IDE?
For example: My project has the recommendation to turn off xml validations, don't install m2eclipse.
Because of eclipse's performance some devs use IntelliJ.
UPDATED:
For these who feel uncomfortable with the eclipse's performance I suggest to try other solutions just to have comparison - I tried and this was the best what I've done in performance subject :)
Remove unwanted activation of some of the plugins at start-up by going to windows-->preference-->General-->Startup and shutdown.
Also make sure you don't use those plugins in any of your views
Eclipse is not a word processor. Better to disable the spell check. Disabling spell check will reduce the eclipse burden by going to Windows-->Preference-->General-->Editors
--> Text Editors-->Spelling
When eclipse builds the project, it will delete all output folders and rebuild classes built by other compilers. We can disable such features, as deleting the output folders and rebuilding will take sometime. Goto Windows-->Preference-->Java-->Compiler-->Building
Disabling label decorations which is of less use for you, will also help you to gain some performance . Goto Windows-->Preference-->General-->Appearance-->Label
Decorations
Close unwanted projects and use working set option to move from one group of
project to another smoothly.
You could also disable Eclipse automatic building, if it is not needed for you.
Goto Project-->Build Automatically (uncheck it)
Do not keep lot of tabs opened in the editor. Better to have around 20 tabs .
Regularly close the unused tabs. To open resource we can always use ctrl+shift+R and
ctrl+shift+T (java resource) instead of opening lot of tabs
Disable unwanted plugins. Full J2EE eclipse version has an option to disable/uninstall plugins. Goto Help-->Software Updates-->Manage Configuration. Right click on any installed plugin to get disable option. If this option is not available then enable Classic Update by going to Windows-->Preference-->Capabilty and check classic update. Now the manage configuration option should be available in help menu
I'm an intelliJ user though occasionally peep into eclipse since I like to use it. Couple of things you can try which my work colleague pointed to are
Show the heap status (General -> Show heap status) can keep an eye on memory and hit the button to clear!
In project properties set the default output folder to be outside of the target
Workspace options, unchecking build automatically (build in the background as soon as you hit Save (Ctrl+S)), refresh automatically & save auto before build. You may have you own preferences but can give it a try.
Show sleeping/hidden tasks to see whats going on underneath?
You must have already tried giving it more memory I guess. Hopefully it will improve.
Ensure you have enough memory and that Eclipse is actually using it (add -Xms -Xmx arguments at Eclipse start).
Remove all plug-ins, you dont use.
Create separate workspace for projects you change rarely and include them as JARs to your primary project.
Use debug mode only when you are debugging (it is slower and uses more memory).
Put all validators (preferences > Validation) to 'Manual' and deselect 'Build'.
Also, consider using an external svn client (like Tortoise) instead of an eclipse plugin like subclipse:
Subclipse consumes so much system resources and effects eclipse performance greedily in big projects. If you could, consider not to use subclipse especially in projects that contain thousands of code kept in subversion source repository. It's really become a very heavy-weight plug-in with heavy-weight code.
Add the source and output directory trees to your Virus Scanner's exclusion list.
1.Disable unecessary validations and startup action in eclipse reference.
For validations: on eclipse menu Windows -> Preferences -> Validation, click “Disable All”, and then select the validator which you need. I selected “Classpath Dependency Validator” only.
For startup action: on eclipse menu Windows -> Preferences, type “startup”, select “Startup and Shutdown”, untick the options you don’t need.
2.Modify eclipse.ini(set the Xmn(new generation size), Xms and Xmx, enable parallel GC)
Change or add the following settings given below
-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:+UseParallelGC
If you have a lot of projects open, it might help to close unused projects. It helps a lot, as Eclipse does not have to provide all the memory model required for content assist.
Disable 'Build Automatically' in the Project menu and set up a key binding for Build Project instead, e.g. CTRL + B. I've tried so many different things to improve Eclipse performance, but this is the only one that really works for me.
Getting slow performance usually is a problem of one or more badly implemented plugins. Identifying the bad plugin and uninstalling it normally removes the bad performance (of course if you realy NEED the plugin you are out of luck ;) ).
I am debugging a large program containing lots of breakpoints. I have heavily increased Eclipse's performance while debugging by disabling the breakpoints at startup, and only enabling them again just before I need them.

Categories

Resources