Netbeans provides a lot of custom "hints", which are like warnings, only that most of them can't be suppressed (just disabled IDE-globally).
But now I looking at code which uses
#SuppressWarnings("element-type-mismatch")
to suppress a hint/warning which is called "suspicious method call" (such as remove(...) for a collection with a "wrong" type).
Well, I would never come to the idea to suppress a hint named "suspicious method call" with a SuppressWarnings-parameter called "element-type-mismatch", but apparently, it works.
So, is there a "magic list" of such parameters?
How, for instance, do I suppress the hint/warning "return of collection field"?
NOTE: for this similar question, "element-type-mismatch" is not listed.
After a brief look at the NB-sourcecode, I found these in some of the java.hint -classes:
#Hint(category="bitwise_operations", suppressWarnings="IncompatibleBitwiseMaskOperation")
#Hint(category="initialization", suppressWarnings="LeakingThisInConstructor")
#Hint(category="logging", suppressWarnings={"NonConstantLogger"}) //NOI18N
#Hint(category="logging", suppressWarnings={"ClassWithMultipleLoggers"}) //NOI18N
#Hint(category="logging", suppressWarnings={"ClassWithoutLogger"}, enabled=false) //NOI18N
#Hint(category="code_maturity", suppressWarnings="UseOfObsoleteCollectionType")
#Hint(category="initialization", suppressWarnings="OverridableMethodCallInConstructor")
#Hint(category="bitwise_operations", suppressWarnings="PointlessBitwiseExpression")
#Hint(category="code_maturity", suppressWarnings="CallToThreadDumpStack")
#Hint(category="bitwise_operations", suppressWarnings="ShiftOutOfRange")
#Hint(category="initialization", suppressWarnings="StaticNonFinalUsedInInitialization")
#Hint(category="code_maturity", enabled = false, suppressWarnings="UseOfSystemOutOrSystemErr")
#Hint(category="code_maturity", suppressWarnings="CallToPrintStackTrace")
Apparently, not all IDE-hints that are displayed as warnings are made suppressable...
Don't know why though, 'cause the AbstractHint class wich many of them extends easily provides this ability...
These are just the suppress-names though, so to find the mapping to the names of the warnings they represent, a deeper dig in the source is needed.
The documentation says:
Compiler vendors should document the warning names they support in conjunction with this annotation type. They are encouraged to cooperate to ensure that the same names work across multiple compilers.
Since NetBeans is using javac I think, here is a list.
See also this question.
If you are using another compiler, or some compiler plugin, search for its documentation.
Well the list is hard to find. Did find the sources of the hint classes of Netbeans.
So the 'list' is here. (also look at the sub packages; e.g. jdk and perf)
All classes can be supressed by using its camel cases name like:
// org.netbeans.modules.java.hints.jdk.UnnecessaryBoxing.java
#SuppressWarnings("UnnecessaryBoxing")
Related
Is it possible to suppress this kind of warning?
Note: I am not looking for suppressing all warnings(like this #SuppressWarnings("all") ), but only the mentioned type.
For Intellij, put this annotation on the class that has the warnings
#SuppressWarnings("SynchronizeOnNonFinalField")
This lead me to the tag to use for suppression and trial and error lead me to put it on the class instead of on the field or synchronized statement. :-P
If you're using IntelliJ, it looks like it's #SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter"). Otherwise it depends. You might find the answer on the list here: What is the list of valid #SuppressWarnings warning names in Java?
Note that the warning is usually correct. In most cases you should just use a final field.
This would help you,
All values are permitted (unrecognized ones are ignored). The list of
recognized ones is compiler specific.
'unchecked' and 'deprecation' are required by the Java Language
Specification, and so should be valid with all compilers. For Sun's
compiler, running 'javac -X' gives a list of all values recognized by
that version. For 1.5.0_17, the list appears to be:
all deprecation unchecked fallthrough path serial finally
Please refer this, same has discussed here What is the list of valid #SuppressWarnings warning names in Java?
Lets take a
val m = "Scala is fun"
IntelliJ helps figure out a lot of things that can be done with this
Is there a way for me to know which of these functions come from Scala and which ones come from Java?
In IDEA's autocompletion, bold entries are methods defined on the type of the object itself, while underlined functions are added by implicit conversions and pimp-my-library (for explanation, see for instance here or search on StackOverflow or Google).
However, for the special case of types which are defined in Java (like String, the type of m), you happen to be right on the Java-vs-Scala distinction: there bold methods are real methods, which must be defined within the type of m (here String) and thus in Java. While pimp-my-library is a Scala pattern, so typically underlined functions will be written in Scala (this is just a rule of thumb, but I've never yet seen an exception).
Non-bold functions are simply inherited.
For the amount of documentation, as a rule of thumb the Java standard library has quite comprehensive documentation (it's supposed to be a specification for the method) while Scala varies typically between less and much less documentation.
I've searched for how to change the fonts used for this highlighting in IntelliJ 11, but I've not found much - you can change fonts used to highlight the code, but I suspect that doesn't make a difference here.
If you have IDEA 12 you can hit Ctrl-Q on any selected method in the pop-up to view "Quick documentation" for that method, not only that, you can traverse the list of methods and the quick doc will change to suit the new selections.
If you find any entries with no quick help, it's a good bet it will be a Scala method ;#)
I'll check for IDEA 11 too.
EDIT: It works for IDEA 11 CE and Ultimate too.
There are at the moment, two ways to mark code as depreacted in java.
Via JavaDoc
/**
* #deprecated
*/
Or as an annotation:
#Deprecated
This is my problem - I find it a bit too much to declare both, when marking a method as deprecated when using Eclipse. I really just want to use one of them.
However does using the annotation give the compiler actual useful additional information?
But only using the annotation, I cannot state why the method is deprecated - I can only do that with JavaDoc, and deprecating a method without specying why is bad.
So, can I only use one of them? Or should I really just learn to specify both?
You should use both. The Annotation allows the compiler to display a warning whenever a deprecated method is used, and the javadoc explains why. Both are important.
As per Oracle's Java Annotations tutorial:
When an element is deprecated, it should also be documented using the Javadoc #deprecated tag...
From the horse's mouth:
NOTE: The Java Language Specification
requires compilers to issue warnings
when classes, methods, or fields
marked with the #Deprecated annotation
are used. Compilers are not required
by the Java Language Specification to
issue warnings when classes, methods,
or fields marked with the #deprecated
Javadoc tag are accessed, although the
Sun compilers currently do so.
So basically, if you want a guarantee that there will be compiler warnings, you need to use the annotation. And because of some API designer's breathtaking incompetence, you need to specify the javadoc tag as well to give an explanation.
Personally, I'd say the annotation is useless and should be omitted until it's fixed, since any good compiler or IDE will display warnings with the javadoc tag as well.
You should write both.
The #Deprecated Anotation is for the Compiler and the #deprecated JavaDoc tag is for the Person who wants to know why this is deprecated.
An example can look like this:
/**
* #deprecated We dont need this Method because ...
*/
#Deprecated
public void doStuff(){..}
You should specify both.
The annotation lets the compiler know about it and trigger warnings when the method is used.
The JavaDoc attribute lets developers know about before they start using it.
These are two very different things!
This can be easily dealt with a good IDE.
Eclipse Neon, for eg. automatically adds #Deprecated annotation, when I create a javadoc #deprecated on a method or field.
So I simply write the javadoc with the appropriate explanation and let the IDE take care of adding the #Deprecated annotation, the minute I save the file.
I have read about Java Reflections but till date it has been a vague concept to me. Can someone give a brief details with short example on how to use reflections in Java ?
Thanks.
I have read about Java Reflections but
till date it has been a vague concept
to me.
Here is a quick into to reflection in java:
Structural introspection. Basic reflection deals with the introspection of object at run-time. This means that you can learn the structure of objects and classes at run-time programmatically, e.g. get the class of the object, list the methods of the class, list the fields defined in the class, etc.
Reflective invocation and instantiation. With reflection you can invoke a method at run-time which is not defined at compile-time, e.g. invoke method named M on object O, where M is read in a configuration file. You can also instantiate object dynamically without knowing the class at compile-time.
Annotations. Then you can move one level up in the meta levels, and play with annotations. Annotations describe other elements such as class, method and fields. Many framework rely on this.
Dynamic proxy. Dynamic proxy can be generated at run-time. In this case, it's really like if you create a class dynamically at run-time. To use with care, but definitively handy and powerful in some cases.
I guess you will start with structural introspection. There are links to tutorials in the other answers, but I hope this gives you an overview of what else can be done.
I guess the article 'Using Java Reflection' found on sun.com might be a good starting point.
It's primarily to be used to access classes/methods/fields programmatically (i.e. during runtime instead of compiletime). Good real world API's which uses reflection intensively are ORM's like Hibernate/JPA.
You can find here a Sun tutorial on the subject (click Next link at the bottom to paginate through it).
Something worth mentioning as well is Javassist. Not only does it have reflective abilities, but it also allows run-time bytecode manipulation using ordinary source syntax! Once you've gotten into reflection a bit more (which you probably have by now), you'll truly appreciate it's beauty.
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?
What are their typical usages?
Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks.
Oracle has a good explanation of the concept and its meaning in Java on their site.
Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have attributes which are the same thing.
Their use is quite diverse. One typical Java example, #Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.
Anders gives a good summary, and here's an example of a JUnit annotation
#Test(expected=IOException.class)
public void flatfileMissing() throws IOException {
readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat");
}
Here the #Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown.
Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code.
Here is an introduction.
To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor.
They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...).
The first thing a newcomer to annotations will ask about annotations is: "What is an annotation?" It turns out that there is no answer to this question, in the sense that there is no common behavior which is present in all of the various kinds of java annotations. There is, in other words, nothing that binds them together into an abstract conceptual group other than the fact that they all start with an "#" symbol.
For example, there is the #Override annotation, which tells the compiler to check that this member function overrides one in the parent class. There is the #Target annotation, which is used to specify what kinds of objects a user defined annotation (a third type of construct with nothing in common with other kinds of annotation) can be attached to. These have nothing to do with one another except for starting with an # symbol.
Basically, what appears to have happened is that some committee responsible for maintaining the java language definition is gatekeeping the addition of new keywords to the java language, and therefore other developers are doing an end run around that by calling new keywords "annotations". And that's why it is hard to understand, in general what an annotation is: because there is no common feature linking all annotations that could be used to put them in a conceptual group. In other words, annotations as a concept do not exist.
Therefore I would recommend studying the behavior of every different kind of annotation individually, and do not expect understanding one kind of annotation to tell you anything about the others.
Many of the other answers to this question assume the user is asking about user defined annotations specifically, which are one kind of annotation that defines a set of integers or strings or other data, static to the class or method or variable they are attached to, that can be queried at compile time or run time. Sadly, there is no marker that distinguishes this kind of annotation from other kinds like #interface that do different things.
By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools.
When do you use Java's #Override annotation and why?
The link refers to a question on when one should use the override annotation(#override)..
This might help understand the concept of annotation better.Check out.
Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API
for example you need to call transaction method for a bank transfer :
without using annotation :
the code will be
transfer(Account account1, Account account2, long amount)
{
// 1: Call middleware API to perform a security check
// 2: Call middleware API to start a transaction
// 3: Call middleware API to load rows from the database
// 4: Subtract the balance from one account, add to the other
// 5: Call middleware API to store rows in the database
// 6: Call middleware API to end the transaction
}
while using Annotation your code contains no cumbersome API calls to use the middle-
ware services. The code is clean and focused on business logic
transfer(Account account1, Account account2, long amount)
{
// 1: Subtract the balance from one account, add to the other
}