Convert existing generics to diamond syntax

安稳与你 提交于 2019-11-30 12:30:42

问题


I rather like the diamond syntax for generics that Java 7 introduces - not so much from a time saving perspective (after all most IDEs fill that bit in for you anyway) but just because it makes the code look a bit cleaner. Because of this and other reasons (mainly the fact I'm developing a new piece of software and some of the new APIs in Java 7 will be useful) I'm most likely going to switch the existing codebase to use / require Java 7.

However there's a fair chunk already written pre-diamond syntax, and I'd like to consistently use the diamond syntax throughout. Is there an IDE shortcut (I'm using Netbeans but obviously can open the project in any free IDE to do the task) or something else that can automatically switch the existing generic code to use diamond syntax?


回答1:


Oh yes, I have successfully done this on IntelliJ (free Community Edition).

Menu > Analyze > Inspect Code...

In the result, select "Java language level migration aids > Explicity type can be replaced with <>"

Right click, run "Apply Fix 'Replace with <>'" And you got diamonds.

There was a bug about diamond on anomymous classes, so some code may not compile after the fix. You'll have to revert them back then.

// anonymous class, <> doesn't work.
new Factory<Pig>(){ ... }  
// however IntelliJ may wrongly "fix" it to
new Factory<>(){ ... }   // does not compile.



回答2:


If you just want to analyze diamonds and not all the other inspections, use IntelliJ IDEA 12 and go to:

Analyze > Run Inspection by Name... > type "explicit type can be replaced with <>" into the prompt that opens > select the drop down entry and hit Enter

After the inspection runs, you can choose to apply the fix in the Inspection tab at the bottom of the screen.

This is way faster than running every code inspection by using regular 'Analyze > Inspect Code...'




回答3:


Using Eclipse, you can use a find/replace using regular expressions.

Search for:

new (\w+)<.+>

And replace for:

new $1<>

This will also replace any anonymous inner classes, so compilation errors might occur.




回答4:


Eclipse detects redundant type arguments and offers a quick fix to remove them and create a diamond, see http://thecoderlounge.blogspot.com/2011/07/java-7-support-in-eclipse-jdt-beta-part_22.html




回答5:


This can be done using Netbeans build-in feature "Inspect and Transform".

  1. Open Refactor -> Inspect and Transform
  2. Use Single Inspection: Can Use Diamond
  3. Click Inspect
  4. Click Do Refactoring



回答6:


You can also use the eclipse "Clean Up" tool. (Source -> Clean Up, tab: Unnecessary Code, "Remove redundant type arguments")



来源:https://stackoverflow.com/questions/6796545/convert-existing-generics-to-diamond-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!