Missing annotation: #Override is not shown by compiler in Eclipse IDE - java

This is kind of weird! but when I implement Collection for my modal class and add unimplemented methods using Eclipse IDE, it is not showing #Override in any of the methods which are generated by clicking on "Add Unimplemented Methods".
public class MadeItACollection implements Collection{
}
When I click on "Add Implemented Methods" the following happens:
public class MadeItACollection implements Collection{
public int size() {
// TODO Auto-generated method stub
return 0;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
.
.
.
.
}
I dont see any #Override. I am compiling my codebase in Java 8. Am I missing something obvious?

As peoples' comments suggest, this is a Code Style option within Eclipse.
You can enable it under Preferences -> Java -> Code Style -- ensure that the "Add #Override annotation for new overriding methods" is checked; after, you can also look into adding it for implementations of interface methods via the link directly underneath. (You can also enable automatic adding of the annotation as a Cleanup or Save action in these menus.)

The #Override annotation isn't strictly required when implementing an interface mainly because you aren't overriding any superclass implementation you are actually implementing the interfaces declared methods. So maybe a #Implements annotation is required, but that's a whole different topic of conversation.
However, it is strongly recommended that you still use the #Override annotation on these methods because:
It explicitly conveys to anybody reading the code that it is an overriding method.
It helps avoid shooting yourself in the foot by throwing a compile time error if you misspell the method you want to override because it will tell you if the method can actually override an existing super method.
Most IDEs actually will help you add this automatically:
Intellij Idea:
Navigate to
File => Settings => Editor => Code Style => Java
And scroll to Override Method Signature and you should find Insert #Override annotation, make sure this is checked.
The Jetbrains documentation says the below about this setting option:
Insert #Override Annotation: Select this checkbox to have IntelliJ IDEA insert #Override annotations automatically.
Eclipse:
Navigate to:
Window => Preferences => Java => Code Style
And look for Add #Override annotation for new overriding methods and make sure it has been checked.
You can also add it as a Save Action by navigating to:
Window => Preferences => Java => Editor => Save Actions
And ensuring that Perform the selected actions on save has been selected and that Additional actions has been selected and ensuring that Add missing Annotations has been configured

Related

Ignore all checkstyle warnings for deprecated classes and methods

Can I somehow ignore any warning for deprecated class?
For example:
I had following warnings AvoidEscapedUnicodeCharacters, NonEmptyAtclauseDescription for deprecated class.
How to ignore all of them?
Checkstyle allows you to write your own custom filters. You can use SuppressWarningsFilter as a basis, because this filter is filtering based on annotations as well. You'd just need to change the annotation that you're looking for.
public class SuppressWarningsFilter
extends AutomaticBean
implements Filter {
#Override
protected void finishLocalSetup() {
// No code by default
}
#Override
public boolean accept(AuditEvent event) {
return !SuppressWarningsHolder.isSuppressed(event);
}
}
Pretty simple, but all of the logic is in SuppressWarningsHolder. That code is a few hundred lines, but you should be able to copy and paste a lot of it, and probably remove a large chuck as well.
I've implemented this: https://github.com/michaelboyles/checkstyle-annotation-filter. I'll make it available via the central repository at some point.
You just need to add the line below:
#SuppressWarnings("deprecation")
It will ignore all deprecated methods in your code.
I hope this will help.

Find Method usages only for specified class in Intelij-Idea

I am using IntelliJ IDEA and I have problem with method usage finding.
Suppose I have interface Worker.
public interface Worker {
void startWork();
void endWork();
}
And I have two implementations.
public class Develper implements Worker {
#Override
public void startWork() {
System.out.println("Developer Start Working");
}
#Override
public void endWork() {
}
}
public class Qa implements Worker {
#Override
public void startWork() {
System.out.println("QA start Work");
}
#Override
public void endWork() {
}
}
I open the Developer class and trying to find usages of startWork().
I want only to view usage of the Developer.startWork() implemented method.
But when I find usages it shows both Developer and Qa.startWork() method usages. How can I avoid Qa.startWork() method usage when finding Developer.startWork() usages?
Using Ctrl+Shift+Alt+F7 (⌘+⇧+⌥+F7 for Mac) should show the prompt from Jim Hawkins answer.
See: https://www.jetbrains.com/help/idea/find-usages-method-options.html
When you search for usages of a method implementation with this dialog Ctrl+Shift+Alt+F7, IntelliJ IDEA will ask whether or not you want to search for the base method. With any other find usages actions such as Alt+F7 or Ctrl+Alt+F7, the base method will be included in the search results automatically.
I'm using IntelliJ IDEA 15.0.1 .
I think what you see when using the "find usages" functionality depends from the context.
If you place the cursor in method name Developer.startWork and invoke find usages , you should see a small dialog. You are asked "Do you want to find usages of the base method?" .
If you say "No", and in your sources you did only call the method via the base class or interface (Worker.start() in your example), IDEA doesn't show you any hits. Thats correct.
If you call the overridden method via Developer.startWork() , and press "No" in the dialog, then you will see the usages of the specific implementation.
Update:
After reading the answer from #JimHawkins, I think the elephant is still in the room :) The question is, do you want to see where Developer.startWork() is actually called, or do you want to see where it is statically referenced?
Eg:
Developer developer = new Developer();
developer.startWork(); // you want to find only this?
Worker worker = developer;
worker.startWork(); // ..or this as well?
The find usages method can only tell, where a given method is statically referenced, but not where it is actually used (that is determined runtime via the mechanism of polymorphism).

Unclear inspection warning "NullableProblems" in IntelliJ

Why am I getting a warning from the "NullableProblems" inspection in IntelliJ on this:
public class Test implements Comparable<Test> {
#Override
public int compareTo(Test o) {
return 0;
}
}
I'm using IntelliJ 14.1.4 and compiling with Java 1.7
Screenshot:
Adding #NotNull before the argument doesn't help:
From Comparable.compareTo:
#throws NullPointerException if the specified object is null
So IntelliJ knows, that the object should not be null and adds a #NotNull annotation automatically:
IntelliJ IDEA will look carefully at SDK and libraries bytecode and will infer these annotations automatically so that they can later be used to analyze source code to spot places where you overlooked null.
Your overriden method doesn't include this annotation, so it overrides this behavior making the parameter nullable - against the contract of the Comparable interface.
You can solve this by adding #NotNull before the parameter.
You can also disable this inspection by pressing Alt + Enter, selecting the warning in the popup menu and selecting Disable inspection in the sub-menu.
Check out the Web Help and this thread for more information about #NotNull / #NonNull annotations.
This can be globally configured in IntelliJ IDEA easily and for me personally is the recommended way. If you want you can add your own annotations.
i.e. javax.validation.constraints.NotNull
Path to the setting:
Settings > Editor > Inspections > #NotNull/#Nullable problems > Configure annotations
Some screenshots:
Its because that you are overriding a method that does not have a #NotNull annotation.
IntelliJ IDEA warns you if the overriding method does not have a #NotNull annotation.

Unnecessary #SuppressWarnings("unused")

I'm getting a compiler warning for the #SuppressWarnings annotation in eclipse for the code:
#Override
public boolean doSomething(#SuppressWarnings("unused") String whatever) throws AnException {
throw new AnException("I'm still in bed and can't do anything until I've had a shower!");
}
It looks like a yellow squiggle under the word "unused" and on mouse hover I get the tooltip Unnecessary #SuppressWarnings("unused").
I think another developer is being prompted to put in these annotations by eclipse and I'm basically being prompted to take them out. How can I configure eclipse to prompt me to put the #SuppressWarnings annotation in instead of it complaining about it?
If anyone would like to comment on best practice here then that would also be most welcome.
In the code in your question, the #SuppressWarnings("unused") annotation is unnecessary because the method is either overriding another method from a superclass or implementing an interface. Even if you don't actually use the whatever parameter it's mandatory to declare it, otherwise the #Override annotation will produce an error (you'd be changing the signature of the overridden method if you removed the parameter.)
In some older versions of Eclipse the code as shown would not cause a warning, but in more recent releases it does. I believe it's a valid warning, and I'd rather remove the #SuppressWarnings("unused") in this case.
Go to
Window → Preferences → Java → Compiler → Errors/Warnings → Annotations.
And select Ignore for Unused '#SuppressWarnings` token.
Alternatively, if you think it's more correct to delete the SuppressWarnings annotation:
Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Unnecessary code -> Value of parameter is not used
and select Ignore in overriding and implementing methods
In my code there's no inheritance defining the 3 methods with #SuppressWarnings("unused")
This code gives 'Unnecessary #SuppressWarnings("unused")' in Eclipse Juno (latest version), but if I remove the #SuppressWarnings("unused"), I get "Constructor/Method is never used" warnings in IntelliJ IDEA 11.1.3
The methods aren't directly used in the project, only by 3rd party products Jackson, JAXB & GSON, so IntelliJ is right, I would say ...
public class EmailUnsendable extends SkjemaError {
private NestedCommand command; // Can't be Command (interface) because of GSON!
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public EmailUnsendable() {
}
public EmailUnsendable(String referenceNumber, String stackTrace, NestedCommand command) {
super(referenceNumber, stackTrace);
this.command = command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public NestedCommand getCommand() {
return command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public void setCommand(NestedCommand command) {
this.command = command;
}
}
I believe this is an error in Eclipse.

Is it safe to comment out the "#Override"?

To get my code to compile - which contained the following:
public class ContactsActivity extends ListActivity implements AdapterView.OnItemClickListener {
Cursor mContacts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Return all contacts, ordered by name
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Display all contacts in a ListView
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, mContacts,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
// Listen for item selections
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
. . .
...I had to comment out the "#Override" above the onItemClick() event handler. Is this safe? Should I just shrug my shoulders and say, "OK, that works, I'll forget about it" or is there evil afoot/a hidden problem lurking?
as per my suggestion, it is not good to remove that line. you need to change to JDK version in your eclipse then you will not get such errors. Follow, following steps for it,
Right Click on your Project & select Properties.
Then from the left section Select Java Compiler & select the Version of the JDK you installed. If it is already selected then de-select it & try it.
If you had to comment out the #Override, then your compiler's JDK compliance level isn't set to 1.6, which it should be for Android development. If you're using Eclipse, right click on the project name and select "Properties". Then select "Java Compiler" and adjust as necessary. (You probably inherited a lower JDK compliance level from the workspace. If appropriate, change the compliance level for the workspace instead. This will save having to fix the same problem with new projects.)
But to answer your question: it's safe to comment out #Override. It's just not so great to be using a lower compliance level.
You java version is set to less than 1.6. Starting there, interfaces and not just methods can be market as Override. Right click the project -> Properties -> Java Compiler -> Compiler compliance level to 1.6
From the Java docs:
#Override - the #Override annotation informs the compiler that the
element is meant to override an element declared in a superclass
(overriding methods will be discussed in the the lesson titled
"Interfaces and Inheritance").
// mark method as a superclass method
// that has been overridden
#Override
int overriddenMethod() { }
While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override
fails to correctly override a method in one of its superclasses, the
compiler generates an error.
It depends. If your compiler is set to target java 5, and the onCreate method is inherited from the interface then yes. Java 5 doesn't support the override annotation on interface methods, whereas Java 6 expects it. This may itself be an indication that your JDK is set up wrong, if you're expecting to target Java 6, what you may be getting is Java 5.
if you'd commented it out, you would not override the methods. So you'd actually do nothing. (My opinion)

Categories

Resources