- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot
![](http://omraadeinfo.online/777/templates/cheerup1/res/banner1.gif)
The @SuppressWarnings Annotation in Java
- The @Override Annotation in Java
- @SafeVarargs Annotation in Java 9 with Example
- Java - @Target Annotations
- Java @Retention Annotations
- Spring @Bean Annotation with Example
- Annotations in Java
- Spring AOP - AspectJ Annotation
- Spring @Service Annotation with Example
- Spring @Primary Annotation
- Spring @Required Annotation with Example
- The @Deprecated Annotation in Java
- Spring @Component Annotation with Example
- Spring @Autowired Annotation
- Spring @Repository Annotation with Example
- Spring @Controller Annotation with Example
- Spring @Configuration Annotation with Example
- Spring - Stereotype Annotations
- Spring @ResponseBody Annotation with Example
- Spring @Lazy Annotation
Annotations are a very important part of Java in modern technologies, Most of the technologies such as Hibernate, Spring, Spring Boot, JPA, and so Many other Libraries are using annotations and making developers’ life a lot easy. In Java, built-in General Annotations are –
- @Deprecated
- @FunctionalInterface
- @SuppressWarnings
Syntax: The signature for Java @SuppressWarnings annotation is as follows:
As we can see, the above signature has only one element, which is Array of String, with multiple possible values.
All annotations have two properties :
- Target (@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })) – It will be used with almost everything, wherever you want to suppress warnings.
- Retention (@Retention(value=SOURCE)): Retention policy of functional Interface “SOURCE”, which means annotation won’t go till compiler.
Illustrations:
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code.
This annotation is dangerous because a warning is something potentially wrong with the code. So if we’re getting any warning, the first approach should be resolving those errors. But if we’re suppressing any warnings, we have to have some solid reason. The reason should be commented near to the annotation every time it is used.
Possible Values Inside @SuppressWarnings Annotation Element are as follows:
Description | |
---|---|
All | It will suppress all warnings. |
Cast | Suppress the warning while casting from a generic type to a nonqualified type or the other way around. |
Deprecation | Ignores when we’re using a deprecated(no longer important) method or type. |
divzero | Suppresses division by zero warning. |
empty | Ignores warning of a statement with an empty body. |
unchecked | It doesn’t check if the data type is Object or primitive. |
fallthrough | Ignores fall-through on switch statements usually (if “break” is missing). |
hiding | It suppresses warnings relative to locals that hide variable |
serial | It makes the compiler shut up about a missing serialVersionUID. |
finally | Avoids warnings relative to finally block that doesn’t return. |
unused | To suppress warnings relative to unused code. |
Note: The primary and most important benefit of using @SuppressWarnings Annotation is that if we stuck because of some known warning, then this will ignore the warning and move ahead. E.g. – d eprecated and unchecked warnings.
Please Login to comment...
Similar reads, improve your coding skills with practice.
What kind of Experience do you want to share?
- Prev Class
- Next Class
- No Frames
- All Classes
- Summary:
- Field |
- Required |
- Detail:
Annotation Type SuppressWarnings
Required element summary.
Modifier and Type | Required Element and Description |
---|---|
[] |
Element Detail
Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .
Scripting on this page tracks web page traffic, but does not change the content in any way.
How to suppress unchecked warnings – Java
The ‘unchecked warnings’ is quite popular warning message in Java. However, if you insist this is an invalid warning, and there are no ways to solve it without compromising the existing program functionality. You may just use @SuppressWarnings(“unchecked”) to suppress unchecked warnings in Java.
1. In Class
If applied to class level, all the methods and members in this class will ignore the unchecked warnings message.
2. In Method
If applied to method level, only this method will ignore the unchecked warnings message.
3. In Property
If applied to property level, only this property will ignore the unchecked warnings message.
As conclusion, suppress an unchecked warning is like hiding a potential bug, it’s better to find the cause of the unchecked warning and fix it 🙂
![suppresswarnings unchecked assignment java-json-tutorials](https://mkyong.com/images/json-tutorial-image.png)
Java JSON Tutorials
Parsing JSON with Jackson, Moshi, Gson etc.
About Author
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.stringtemplate.v4.ST;
public class JSONDemoR3 { // Compare files\ // User File static String baseDir = “C:\\Json\\”; static String userJsonFilePath = baseDir + “UserReqest.txt”; // Kibana file static String kibanaJsonFilePath = baseDir + “kibana_mapper.txt”;
static Map mapContentUserRequestKeyValue = new HashMap();
public static void main(String args[]) throws IOException { compareJsonFile(); }
static String readKibanaMapperFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); }
public static void compareJsonFile() throws IOException { // User File readSectionJson(userJsonFilePath); String content = readKibanaMapperFile(kibanaJsonFilePath, StandardCharsets.UTF_8); ST renderJson = new ST(content); for(Map.Entry map : mapContentUserRequestKeyValue.entrySet()) { renderJson.add(map.getKey(), map.getValue()); } generateUserRequestFile(renderJson.render());
private static void generateUserRequestFile(String userRequestFileJson) throws IOException { try (FileWriter file = new FileWriter(baseDir + “User_Request__” + System.currentTimeMillis() + “.json”)) { file.write(userRequestFileJson); System.out.println(“User Request Json file has been generated successfully…”); } } private static void readSectionJson(String file) { JSONParser parser = new JSONParser(); try { FileReader fileReader = new FileReader(file); JSONObject sourceJson = (JSONObject) parser.parse(fileReader); JSONArray jsonSectionArray = fetchSectionArray(sourceJson); JSONObject sectionJson = null; JSONArray fieldsJsonAry = null; @SuppressWarnings(“unchecked”) Iterator arrayIterator = jsonSectionArray.iterator(); while (arrayIterator.hasNext()) { sectionJson = (JSONObject) arrayIterator.next(); fieldsJsonAry = fetchFieldsArray(sectionJson); iteratorFields(fieldsJsonAry); }
} catch (Exception expReadJson) { expReadJson.printStackTrace(); } }
private static JSONArray fetchSectionArray(JSONObject json) { return (JSONArray) json.get(“sections”); }
private static JSONArray fetchFieldsArray(JSONObject sectionJson) { return (JSONArray) sectionJson.get(“fields”); }
private static void iteratorFields(JSONArray jsonFieldArray) { JSONObject fieldJson = null; @SuppressWarnings(“unchecked”) Iterator arrayIterator = jsonFieldArray.iterator(); while (arrayIterator.hasNext()) { fieldJson = (JSONObject) arrayIterator.next(); mapContentUserRequestKeyValue.put(fieldJson.get(“id”).toString(), fieldJson.get(“value”)); } } }
Greetings! Thanks for the solution 2 solution suited for applctn when i tried to use @SuppressWarnings(“unchecked”) it still says previous uncheked warning why!
give me more briefing on sol1 and sol2 if sol1 used any problem to the desired result? thanks in advance!
Sol1 apply to the class level, pls provide your code.
sir i am working on jdk ver 6.0 I am getting a type unchecked warning when i am compiling a code what to do to remove a error
It caused by the generic data type is undefined in your List.
Solution ..
1. Add @SuppressWarnings(“unchecked”) to ignore the checking.
2. Declare the data type for your List
![suppresswarnings unchecked assignment Learn IT University](https://learn-it-university.com/wp-content/uploads/2023/09/small-transparrent-logo.png)
Learn IT University
Understanding the suppresswarnings(“unchecked”) annotation in java.
![suppresswarnings unchecked assignment](https://learn-it-university.com/wp-content/uploads/2024/05/java-duke.jpg)
In Java, the `@SuppressWarnings(“unchecked”)` annotation is used to inform the compiler to ignore unchecked warnings that occur when working with raw types in generics. These warnings are typically seen when the compiler encounters code where type safety cannot be guaranteed.
Sometimes Java generics just doesn’t allow certain operations without generating warnings. In such cases, you might have to assure the compiler that the operations being performed will indeed be safe at runtime.
This often happens when dealing with legacy code or libraries that do not use generics, or when mocking a generic interface in unit tests. Although it’s usually best practice to resolve the root cause of these warnings, occasionally this would introduce unnecessary complexity into the code. Hence, marking those sections with @SuppressWarnings(“unchecked”) may sometimes be the neater solution.
![suppresswarnings unchecked assignment](https://learn-it-university.com/wp-content/uploads/2024/05/free-courses-banner-scaled.jpg)
It’s crucial to add explanatory comments whenever you use this annotation to provide clarity on why type safety cannot be enforced and to assist any other developer who might work on the same codebase.
Here’s a practical example:
In the above example, we deal with a raw list, which can lead to an unchecked conversion warning when we attempt to cast it to a parameterized type. The `@SuppressWarnings(“unchecked”)` annotation helps us suppress this specific warning.
- Increased Compilation Overhead: Excessive reliance on unchecked operations can obscure potential type safety issues, leading to possible runtime exceptions.
- Documentation: Always document why you’re using `@SuppressWarnings(“unchecked”)`, mentioning the context and reasons, for future reference.
![suppresswarnings unchecked assignment](https://learn-it-university.com/wp-content/uploads/2024/05/support-on-pateron-banner-scaled.jpg)
Tagged in :
![suppresswarnings unchecked assignment Andrii Piatakha Avatar](https://learn-it-university.com/wp-content/uploads/2024/05/cropped-Snapinsta.app_272266597_2123624187787176_2653205608166250337_n_1080-1-100x100.jpg)
Andrii Piatakha
1 M Students Worldwide
Support me on Patreon and get access to exclusive content
Latest Posts
![suppresswarnings unchecked assignment](https://learn-it-university.com/wp-content/uploads/2023/11/Template-for-pictures-in-articles.jpg)
Creating an Empty Stream in Java: A Step-by-Step Guide
![suppresswarnings unchecked assignment](https://learn-it-university.com/wp-content/uploads/2023/11/duke0.png)
Using Retrofit 2 to Handle URL Query Parameters in Android Development
How to remove an item from an arraylist in java, choosing the right archetype for a simple java project, configuring jvm arguments for visualvm usage.
- Coding Exercises (13)
- FREE Courses (1)
- Learn Java in 3 Minutes (3,990)
- WiseBullAI (3,847)
android annotations arraylist arrays class collections Concurrency date datetime Eclipse enums exception file generics gradle hashmap hibernate intellij-idea Interface jackson jar java java-8 java-stream jpa json JUnit jvm lambda list maven maven-2 mockito Multithreading oop performance Reflection regex Spring spring-boot spring-mvc static String unit-testing xml
More Articles & Posts
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
@SuppressWarnings in generic array declaration
While doing a coding test, I ran into a problem where I need to initialize an array of generic type in Java. While trying to figure out how to do that, I looked at this Stack Overflow question and it requires that I suppress a warning which doesn't seem like a good practice, and might have other type safety issues. For clarity, here is the code:
Does this mean I am going about the problem wrong? Is it ok to have the @SuppressWarnings("unchecked") in this case?
Should I just use an ArrayList ?
- programming-practices
3 Answers 3
@SuppressWarnings("unchecked") is sometimes correct and unavoidable in well-written code. Creating an array of generic types is one case. If you can work around it by using a Collection<T> or List<T> of generics then I'd suggest that, but if only an array will do, then there's nothing you can do.
Casting to a generic type is another similar case. Generic casts can't be verified at runtime, so you will get a warning if you do, say
That doesn't make it bad style to have generic casts. It simply reflects a limitation of the way generics were designed in Java.
To acknowledge that I'm intentionally writing code with warnings, I've made it a rule to add a comment to any such lines. This makes the choice stand out. It also makes it easy to spot these lines, since @SuppressWarnings can't always be used directly on the target lines. If it's at the top of the method it might not be obvious which line or lines generate warnings.
Also, to be clear, you should not work around this with a raw type ( List instead of List<T> ). That is a bad idea. It will also produce warnings if you enable -Xlint , so wouldn't really make the situation any better, anyways.
- 4 I'll have to disagree on 'converting' the @SuppressWarnings annotation to a standard comment. For starters, @SuppressWarnings can be used on the specific lines, not just for methods. Second, if you ever did fix the unchecked casting in the future, a good IDE (settings-dependent) will helpfully point you out that the annotation is no longer required. Third, and depending on your school of thought, comments tend to snowball to become its own form of 'comment smell' in the long run, which may lead to misunderstandings. – h.j.k. Sep 26, 2014 at 2:08
- That's a good point. It can be used on variable declarations, but not on statements in general. I've edited my example to show a line that can't be annotated. I personally don't use an IDE (nor do any of my coworkers), so if javac doesn't catch it, I comment it. I'll admit I'd probably forgo these comments if we all used IDEs. – John Kugelman Sep 26, 2014 at 2:26
- Yeah, I over-generalized by saying specific lines when the closest is actually variable declarations, as you have mentioned. Just in case anyone needs to consult the API (circa September 2014): docs.oracle.com/javase/8/docs/api/java/lang/… Now I see where you are coming from... – h.j.k. Sep 26, 2014 at 2:34
- You are correct, there are certain things that a human can look at and know are not risky and therefor should have that annotation but a compiler or IDE cannot know for sure (unless you are compiling on Skynet). But I would not add a comment: the annotation itself serves the same purpose as a comment. – user22815 Sep 26, 2014 at 4:24
- 1 Due to the issues around Generified types, type erasure and co-variance, arrays are de facto now a deprecated language element. Don't feel bad about having to suppress type warnings when working with arrays; it's perhaps the most appropriate use of "Suppress" of all. – Kilian Foth Sep 26, 2014 at 6:44
Based on the fact you are asking if you should use ArrayList instead, I assume the use of an array is not a requirement. I would use the ArrayList or other collection and rely on interfaces, not implementations, to reference it:
Java generics are in a tough position. On one hand, Java has the self-imposed (but good) goal of being backwards compatible. Since generics are essentially incompatible with pre-1.5 bytecode, this results in type erasure . Essentially, the generic type is removed at compile time and generic method calls and accesses are reinforced with type casts instead. On the other hand, this limitation makes generic references really messy sometimes to the point that you must use @SuppressWarnings for unchecked and raw types at times.
What this means is that collections that rely on method calls to insulate users of a collection from the storage work fine, but arrays are reified which means that per the language, array types must be available at runtime. This runs counter to collections which as I mentioned have the generic type erased. Example:
Despite the reference array2 being declared as Object[] , the JVM knows the array it targets can only hold strings. Because these types are reifable, they are essentially incompatible with generics.
StackOverflow has many questions on the topic of Java generics and arrays, here are a few good ones I found:
- How to: generic array creation
- Generic arrays in Java
In this case, it is perfectly okay to suppress the unchecked cast warning.
It's an unchecked cast because E is not known at runtime. So the runtime check can only check the cast up to Object[] (the erasure of E[] ), but not actually up to E[] itself. (So for example, if E were Integer , then if the object's actual runtime class was String[] , it would not be caught by the check even though it's not Integer[] .)
Array.newInstance() returns Object , and not E[] (where E would be the type argument of the Class parameter), because it can be used to create both arrays of primitives and arrays of references. Type variables like E cannot represent primitive types, and the only supertype of array-of-primitive types is Object . Class objects representing primitive types are Class parameterized with its wrapper class as the type parameter, e.g. int.class has type Class<Integer> . But if you pass int.class to Array.newInstance() , you will create an int[] , not E[] (which would be Integer[] ). But if you pass a Class<E> representing a reference type, Array.newInstance() will return an E[] .
So basically, calling Array.newInstance() with a Class<E> will always return either an E[] , or an array of primitives. An array-of-primitives type is not a subtype of Object[] , so it would fail a runtime check for Object[] . In other words, if the result is an Object[] , it is guaranteed to be an E[] . So even though this cast only checks up to Object[] at runtime, and it doesn't check the part from Object[] up to E[] , in this case, the check up to Object[] is sufficient to guarantee that it is an E[] , and so the unchecked part is not an issue in this case, and it is effectively a fully checked cast.
By the way, from the code you have shown, you do not need to pass a class object to initialize GenSet or to use Array.newInstance() . That would only be necessary if your class actually used the class E at runtime. But it doesn't. All it does is create an array (that is not exposed to the outside of the class), and get elements from it. That can be achieved using an Object[] . You just need to cast to E when you take an element out (which is unchecked by which we know to be safe if we only put E s into it):
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged java programming-practices array generics or ask your own question .
Hot network questions.
- Mismatching Euler characteristic of the Torus
- What do humans do uniquely, that computers apparently will not be able to?
- What is with the different pronounciation of "janai" that consistently happens in "Jojo's Bizarre Adventure"?
- Symbolic solution of trigonometric equation
- How to use Sum properly to avoid problems when the summating limits are undefined?
- Who would I call to inspect the integrity of a truss after an electrician cut into it?
- Why is array access not an infix operator?
- Can someone explain the damage distrubution on this aircraft that flew through a hailstorm?
- I am international anyway
- It suggests vs It would suggest
- is_decimal Function Implementation in C++
- Word for a country declaring independence from an empire
- Does it make sense for giants to use clubs or swords when fighting non-giants?
- Why is "second" an adverb in "came a close second"?
- What data are used to find the final threshold for a medical diagnostic test?
- How to negotiate such toxic competitiveness during my masters studies
- How to make Bash remove quotes after parameter expansion?
- What is the meaning of the 'ride out the clock'?
- Ubuntu Terminal with alternating colours for each line
- Was it known in ancient Rome and Greece that boiling water made it safe to drink and if so, what was the theory behind this?
- Why does mars have a jagged light curve
- Smallest Harmonic number greater than N
- Universal PCB enclosure: what are these cylinders with holes for?
- Why a truly uninformative prior does not exist?
all that jazz
James' blog about scala and all that jazz, list of suppresswarnings arguments.
I hate compiler warnings showing in my IDE. It's messy, and it usually indicates that something is bad. But not always. Sometimes, when working with third party libraries, you can't avoid warnings like unchecked assignments. These are easy to get around though, by using the @SuppressWarnings annotation. The unchecked assignment warning is a standard Java compiler warning. A quick Google will reveal that the name of the unchecked assignment warning to pass to @SuppressWarnings is "unchecked".
IDE's however tend to flag warnings for much more than what the Java compiler flags warnings for. An example that I encountered today is in unit tests, if you have no assertions in your unit test, IDEA will flag a warning telling you so. In my case however, I was using mockito, and my assertions were in the form of verify calls. IDEA does not yet understand mockito, so I am faced with compiler warnings in my code, which, as I said before, I hate. Surely I can use @SuppressWarnings to suppress this warning, but what's its name? Google didn't help me at all here, so I decided to do a little investigation.
After writing a quick shell script that unpacked IDEAs jar files and grepped for the description of the warning, I found that the code that generates these warnings is an IDEA plugin called InspectionGadgets . I found that each warning was checked for by sub classes of com.siyeh.ig.BaseInspection , and that the name of the warning, and its description, can be obtained by instantiating each sub class, and calling methods on them. In the case of my test method with no assertions warning, the class that flagged this was com.siyeh.ig.junit.TestMethodWithoutAssertionInspection , and the name of the warning was JUnitTestMethodWithNoAssertions . I can now suppress my warning.
All that work was probably too much to do for each time that I want to suppress an IDEA warning. So I decided to find every warning, and store it in a table. Obviously I wasn't going to do this manually, so using this neat utility for finding all the classes on the classpath, with a few modifications to limit where it searched, I was able to generate a table of every warning that IDEA can flag. Here it is, sorted in alphabetical order of the description:
Warning Description | Warning Name |
---|---|
"Magic character" | MagicCharacter |
"Magic number" | MagicNumber |
'Comparator.compare()' method does not use parameter | ComparatorMethodParameterNotUsed |
'Connection.prepare*()' call with non-constant string | JDBCPrepareStatementWithNonConstantString |
'Iterator.hasNext()' which calls 'next()' | IteratorHasNextCallsIteratorNext |
'Iterator.next()' which can't throw 'NoSuchElementException' | IteratorNextCanNotThrowNoSuchElementException |
'Statement.execute()' call with non-constant string | JDBCExecuteWithNonConstantString |
'String.equals("")' | StringEqualsEmptyString |
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) | StringBufferMayBeStringBuilder |
'StringBuffer.toString()' in concatenation | StringBufferToStringInConcatenation |
'assert' statement | AssertStatement |
'assertEquals()' between objects of inconvertible types | AssertEqualsBetweenInconvertibleTypes |
'await()' not in loop | AwaitNotInLoop |
'await()' without corresponding 'signal()' | AwaitWithoutCorrespondingSignal |
'break' statement | BreakStatement |
'break' statement with label | BreakStatementWithLabel |
'catch' generic class | CatchGenericClass |
'clone()' does not call 'super.clone()' | CloneDoesntCallSuperClone |
'clone()' does not declare 'CloneNotSupportedException' | CloneDoesntDeclareCloneNotSupportedException |
'clone()' instantiates objects with constructor | CloneCallsConstructors |
'clone()' method in non-Cloneable class | CloneInNonCloneableClass |
'compareto()' instead of 'compareTo()' | MisspelledCompareTo |
'continue' or 'break' inside 'finally' block | ContinueOrBreakFromFinallyBlock |
'continue' statement | ContinueStatement |
'continue' statement with label | ContinueStatementWithLabel |
'default' not last case in 'switch' | DefaultNotLastCaseInSwitch |
'equal()' instead of 'equals()' | MisspelledEquals |
'equals()' between objects of inconvertible types | EqualsBetweenInconvertibleTypes |
'equals()' called on array type | ArrayEquals |
'equals()' called on java.math.BigDecimal | BigDecimalEquals |
'equals()' method which does not check class of parameter | EqualsWhichDoesntCheckParameterClass |
'equals()' or 'hashCode()' called on java.net.URL object | EqualsHashCodeCalledOnUrl |
'final' class | FinalClass |
'final' method | FinalMethod |
'final' method in 'final' class | FinalMethodInFinalClass |
'finalize()' called explicitly | FinalizeCalledExplicitly |
'finalize()' declaration | FinalizeDeclaration |
'finalize()' does not call 'super.finalize()' | FinalizeDoesntCallSuperFinalize |
'finalize()' not declared 'protected' | FinalizeNotProtected |
'finally' block which can not complete normally | finally |
'for' loop may be replaced by 'while' loop | ForLoopReplaceableByWhile |
'for' loop replaceable by 'for each' | ForLoopReplaceableByForEach |
'for' loop where update or condition does not use loop variable | ForLoopThatDoesntUseLoopVariable |
'for' loop with missing components | ForLoopWithMissingComponent |
'hashcode()' instead of 'hashCode()' | MisspelledHashcode |
'if' statement with identical branches | IfStatementWithIdenticalBranches |
'if' statement with negated condition | IfStatementWithNegatedCondition |
'if' statement with too many branches | IfStatementWithTooManyBranches |
'indexOf()' expression is replaceable by 'contains()' | ListIndexOfReplaceableByContains |
'instanceof' a concrete class | InstanceofInterfaces |
'instanceof' check for 'this' | InstanceofThis |
'instanceof' on 'catch' parameter | InstanceofCatchParameter |
'instanceof' with incompatible interface | InstanceofIncompatibleInterface |
'notify()' or 'notifyAll()' called on java.util.concurrent.locks.Condition object | NotifyCalledOnCondition |
'notify()' or 'notifyAll()' while not synced | NotifyNotInSynchronizedContext |
'notify()' or 'notifyAll()' without corresponding state change | NakedNotify |
'notify()' without corresponding 'wait()' | NotifyWithoutCorrespondingWait |
'private' method declared 'final' | FinalPrivateMethod |
'protected' member in 'final' class | ProtectedMemberInFinalClass |
'public' constructor in non-public class | PublicConstructorInNonPublicClass |
'readObject()' or 'writeObject()' not declared 'private' | NonPrivateSerializationMethod |
'readResolve()' or 'writeReplace()' not declared 'protected' | ReadResolveAndWriteReplaceProtected |
'return' inside 'finally' block | ReturnInsideFinallyBlock |
'serialPersistentFields' field not declared 'private static final ObjectStreamField[]' | SerialPersistentFieldsWithWrongSignature |
'serialVersionUID' field not declared 'private static final long' | SerialVersionUIDWithWrongSignature |
'setUp()' does not call 'super.setUp()' | SetUpDoesntCallSuperSetUp |
'setUp()' with incorrect signature | SetUpWithIncorrectSignature |
'setup()' instead of 'setUp()' | MisspelledSetUp |
'signal()' without corresponding 'await()' | SignalWithoutCorrespondingAwait |
'size() == 0' replaceable by 'isEmpty()' | SizeReplaceableByIsEmpty |
'static' method declared 'final' | FinalStaticMethod |
'static', non-'final' field | StaticNonFinalField |
'suite()' method not declared 'static' | SuiteNotDeclaredStatic |
'switch' statement | SwitchStatement |
'switch' statement with too few branches | SwitchStatementWithTooFewBranches |
'switch' statement with too low of a branch density | SwitchStatementDensity |
'switch' statement with too many branches | SwitchStatementWithTooManyBranches |
'switch' statement without 'default' branch | SwitchStatementWithoutDefaultBranch |
'synchronized' method | SynchronizedMethod |
'tearDown()' does not call 'super.tearDown()' | TearDownDoesntCallSuperTearDown |
'tearDown()' with incorrect signature | TearDownWithIncorrectSignature |
'teardown()' instead of 'tearDown()' | MisspelledTearDown |
'this' reference escaped in object construction | ThisEscapedInObjectConstruction |
'throw' caught by containing 'try' statement | ThrowCaughtLocally |
'throw' inside 'catch' block which ignores the caught exception | ThrowInsideCatchBlockWhichIgnoresCaughtException |
'throw' inside 'finally' block | ThrowFromFinallyBlock |
'tostring()' instead of 'toString()' | MisspelledToString |
'wait()' called on java.util.concurrent.locks.Condition object | WaitCalledOnCondition |
'wait()' not in loop | WaitNotInLoop |
'wait()' or 'await()' without timeout | WaitOrAwaitWithoutTimeout |
'wait()' while holding two locks | WaitWhileHoldingTwoLocks |
'wait()' while not synced | WaitWhileNotSynced |
'wait()' without corresponding 'notify()' | WaitWithoutCorrespondingNotify |
'while' loop replaceable by 'for each' | WhileLoopReplaceableByForEach |
* import | OnDemandImport |
Abstract class extends concrete class | AbstractClassExtendsConcreteClass |
Abstract class which has no concrete subclass | AbstractClassNeverImplemented |
Abstract class which has only one direct inheritor | AbstractClassWithOnlyOneDirectInheritor |
Abstract class without abstract methods | AbstractClassWithoutAbstractMethods |
Abstract method call in constructor | AbstractMethodCallInConstructor |
Abstract method overrides abstract method | AbstractMethodOverridesAbstractMethod |
Abstract method overrides concrete method | AbstractMethodOverridesConcreteMethod |
Abstract method with missing implementations | AbstractMethodWithMissingImplementations |
Access of system properties | AccessOfSystemProperties |
Access to non thread-safe static field from instance | AccessToNonThreadSafeStaticFieldFromInstance |
Access to static field locked on instance data | AccessToStaticFieldLockedOnInstance |
Accessing a non-public field of another object | AccessingNonPublicFieldOfAnotherObject |
Annotation | Annotation |
Annotation class | AnnotationClass |
Annotation naming convention | AnnotationNamingConvention |
Anonymous class variable hides variable in containing method | AnonymousClassVariableHidesContainingMethodVariable |
Anonymous inner class | AnonymousInnerClass |
Anonymous inner class may be a named static inner class | AnonymousInnerClassMayBeStatic |
Anonymous inner class with too many methods | AnonymousInnerClassWithTooManyMethods |
Arithmetic operation on volatile field | ArithmeticOnVolatileField |
Array.length in loop condition | ArrayLengthInLoopCondition |
Assignment replaceable with operator assignment | AssignmentReplaceableWithOperatorAssignment |
Assignment to 'for' loop parameter | AssignmentToForLoopParameter |
Assignment to 'null' | AssignmentToNull |
Assignment to Collection or array field from parameter | AssignmentToCollectionOrArrayFieldFromParameter |
Assignment to Date or Calendar field from parameter | AssignmentToDateFieldFromParameter |
Assignment to catch block parameter | AssignmentToCatchBlockParameter |
Assignment to method parameter | AssignmentToMethodParameter |
Assignment to static field from instance method | AssignmentToStaticFieldFromInstanceMethod |
Assignment used as condition | AssignmentUsedAsCondition |
Auto-boxing | AutoBoxing |
Auto-unboxing | AutoUnboxing |
Boolean constructor call | BooleanConstructorCall |
Boolean method name must start with question word | BooleanMethodNameMustStartWithQuestion |
Busy wait | BusyWait |
C-style array declaration | CStyleArrayDeclaration |
Call to 'Collection.toArray()' with zero-length array argument | ToArrayCallWithZeroLengthArrayArgument |
Call to 'Date.toString()' | CallToDateToString |
Call to 'Runtime.exec()' | CallToRuntimeExecWithNonConstantString |
Call to 'String.compareTo()' | CallToStringCompareTo |
Call to 'String.concat()' can be replaced by '+' | CallToStringConcatCanBeReplacedByOperator |
Call to 'String.equals()' | CallToStringEquals |
Call to 'String.equalsIgnoreCase()' | CallToStringEqualsIgnoreCase |
Call to 'String.toUpperCase()' or 'toLowerCase()' without a Locale | StringToUpperCaseOrToLowerCaseWithoutLocale |
Call to 'System.exit()' or related methods | CallToSystemExit |
Call to 'System.getenv()' | CallToSystemGetenv |
Call to 'System.loadLibrary()' with non-constant string | LoadLibraryWithNonConstantString |
Call to 'System.runFinalizersOnExit()' | CallToSystemRunFinalizersOnExit |
Call to 'System.setSecurityManager()' | CallToSystemSetSecurityManager |
Call to 'Thread.dumpStack()' | CallToThreadDumpStack |
Call to 'Thread.run()' | CallToThreadRun |
Call to 'Thread.setPriority()' | CallToThreadSetPriority |
Call to 'Thread.sleep()' while synchronized | SleepWhileHoldingLock |
Call to 'Thread.start()' during object construction | CallToThreadStartDuringObjectConstruction |
Call to 'Thread.stop()', 'suspend()' or 'resume()' | CallToThreadStopSuspendOrResumeManager |
Call to 'Thread.yield()' | CallToThreadYield |
Call to 'Time.toString()' | CallToTimeToString |
Call to 'intern()' on String constant | ConstantStringIntern |
Call to 'notify()' instead of 'notifyAll()' | CallToNotifyInsteadOfNotifyAll |
Call to 'printStackTrace()' | CallToPrintStackTrace |
Call to 'signal()' instead of 'signalAll()' | CallToSignalInsteadOfSignalAll |
Call to Numeric 'toString()' | CallToNumericToString |
Call to String.replaceAll(".", ...) | ReplaceAllDot |
Call to a native method while locked | CallToNativeMethodWhileLocked |
Call to default 'toString()' | ObjectToString |
Call to simple getter from within class | CallToSimpleGetterFromWithinClass |
Call to simple setter from within class | CallToSimpleSetterFromWithinClass |
Calls to 'System.gc()' or 'Runtime.gc()' | CallToSystemGC |
Cast conflicts with 'instanceof' | CastConflictsWithInstanceof |
Cast to a concrete class | CastToConcreteClass |
Casting to incompatible interface | CastToIncompatibleInterface |
Caught exception is immediately rethrown | CaughtExceptionImmediatelyRethrown |
Chain of 'instanceof' checks | ChainOfInstanceofChecks |
Chained equality comparisons | ChainedEqualityComparisons |
Chained method calls | ChainedMethodCall |
Channel opened but not safely closed | ChannelOpenedButNotSafelyClosed |
Character comparison | CharacterComparison |
Checked exception class | CheckedExceptionClass |
Class escapes defined scope | ClassEscapesDefinedScope |
Class explicitly extends a Collection class | ClassExtendsConcreteCollection |
Class explicitly extends java.lang.Object | ClassExplicitlyExtendsObject |
Class explicitly extends java.lang.Thread | ClassExplicitlyExtendsThread |
Class extends annotation interface | ClassExplicitlyAnnotation |
Class extends utility class | ExtendsUtilityClass |
Class may be interface | ClassMayBeInterface |
Class name differs from file name | ClassNameDiffersFromFileName |
Class name prefixed with package name | ClassNamePrefixedWithPackageName |
Class name same as ancestor name | ClassNameSameAsAncestorName |
Class naming convention | ClassNamingConvention |
Class references one of its subclasses | ClassReferencesSubclass |
Class too deep in inheritance tree | ClassTooDeepInInheritanceTree |
Class with multiple loggers | ClassWithMultipleLoggers |
Class with too many constructors | ClassWithTooManyConstructors |
Class with too many fields | ClassWithTooManyFields |
Class with too many methods | ClassWithTooManyMethods |
Class without 'toString()' | ClassWithoutToString |
Class without constructor | ClassWithoutConstructor |
Class without logger | ClassWithoutLogger |
Class without no-arg constructor | ClassWithoutNoArgConstructor |
Class without package statement | ClassWithoutPackageStatement |
ClassLoader instantiation | ClassLoaderInstantiation |
Cloneable class in secure context | CloneableClassInSecureContext |
Cloneable class without 'clone()' | CloneableClassWithoutClone |
Collection added to self | CollectionAddedToSelf |
Collection declared by class, not interface | CollectionDeclaredAsConcreteClass |
Collection without initial capacity | CollectionWithoutInitialCapacity |
Comparable implemented but 'equals()' not overridden | ComparableImplementedButEqualsNotOverridden |
Comparator class not declared Serializable | ComparatorNotSerializable |
Comparison of 'short' and 'char' values | ComparisonOfShortAndChar |
Comparison to Double.NaN or Float.NaN | ComparisonToNaN |
Concatenation with empty string | ConcatenationWithEmptyString |
Conditional expression (?:) | ConditionalExpression |
Conditional expression with identical branches | ConditionalExpressionWithIdenticalBranches |
Conditional expression with negated condition | ConditionalExpressionWithNegatedCondition |
Conditional that can be simplified to && or || | SimplifiableConditionalExpression |
Confusing 'else' branch | ConfusingElseBranch |
Confusing 'main()' method | ConfusingMainMethod |
Confusing 'null' argument to var-arg method | NullArgumentToVariableArgMethod |
Confusing floating-point literal | ConfusingFloatingPointLiteral |
Confusing octal escape sequence | ConfusingOctalEscapeSequence |
Confusing primitive array argument to var-arg method | PrimitiveArrayArgumentToVariableArgMethod |
Connection opened but not safely closed | ConnectionOpenedButNotSafelyClosed |
Constant StringBuffer may be String | StringBufferReplaceableByString |
Constant call to java.lang.Math or StrictMath | ConstantMathCall |
Constant conditional expression | ConstantConditionalExpression |
Constant declared in abstract class | ConstantDeclaredInAbstractClass |
Constant declared in interface | ConstantDeclaredInInterface |
Constant if statement | ConstantIfStatement |
Constant naming convention | ConstantNamingConvention |
Constant on left side of comparison | ConstantOnLeftSideOfComparison |
Constant on right side of comparison | ConstantOnRightSideOfComparison |
Constructor not 'protected' in 'abstract' class | ConstructorNotProtectedInAbstractClass |
Constructor with too many parameters | ConstructorWithTooManyParameters |
Control flow statement without braces | ControlFlowStatementWithoutBraces |
Covariant 'compareTo()' | CovariantCompareTo |
Covariant 'equals()' | CovariantEquals |
Custom ClassLoader | CustomClassloader |
Custom SecurityManager | CustomSecurityManager |
Deserializable class in secure context | DeserializableClassInSecureContext |
Design for extension | DesignForExtension |
Division by zero | divzero |
Double negation | DoubleNegation |
Double-checked locking | DoubleCheckedLocking |
Duplicate condition in 'if' statement | DuplicateCondition |
Duplicate condition on '&&' or '||' | DuplicateBooleanBranch |
Empty 'catch' block | EmptyCatchBlock |
Empty 'finally' block | EmptyFinallyBlock |
Empty 'synchronized' statement | EmptySynchronizedStatement |
Empty 'try' block | EmptyTryBlock |
Empty class | EmptyClass |
Empty class initializer | EmptyClassInitializer |
Enum 'switch' statement that misses case | EnumSwitchStatementWhichMissesCases |
Enumerated class | EnumClass |
Enumerated class naming convention | EnumeratedClassNamingConvention |
Enumerated constant naming convention | EnumeratedConstantNamingConvention |
Enumeration can be iteration | EnumerationCanBeIteration |
Exception class name does not end with 'Exception' | ExceptionClassNameDoesntEndWithException |
Extended 'for' statement | ForeachStatement |
Externalizable class with 'readObject()' or 'writeObject()' | ExternalizableClassWithSerializationMethods |
Fallthrough in 'switch' statement | fallthrough |
Feature envy | FeatureEnvy |
Field accessed in both synchronized and unsynchronized contexts | FieldAccessedSynchronizedAndUnsynchronized |
Field has setter but no getter | FieldHasSetterButNoGetter |
Field may be 'static' | FieldMayBeStatic |
Field name hides field in superclass | FieldNameHidesFieldInSuperclass |
Field repeatedly accessed in method | FieldRepeatedlyAccessedInMethod |
Floating point equality comparison | FloatingPointEquality |
Hardcoded file separator | HardcodedFileSeparator |
Hardcoded line separator | HardcodedLineSeparator |
Hibernate resource opened but not safely closed | HibernateResourceOpenedButNotSafelyClosed |
I/O resource opened but not safely closed | IOResourceOpenedButNotSafelyClosed |
If statement may be replaced by && or || expression | SimplifiableIfStatement |
Implicit call to 'super()' | ImplicitCallToSuper |
Implicit call to array '.toString()' | ImplicitArrayToString |
Implicit numeric conversion | ImplicitNumericConversion |
Import from same package | SamePackageImport |
Incompatible bitwise mask operation | IncompatibleBitwiseMaskOperation |
Infinite loop statement | InfiniteLoopStatement |
Infinite recursion | InfiniteRecursion |
Inner class field hides outer class field | InnerClassFieldHidesOuterClassField |
Inner class may be 'static' | InnerClassMayBeStatic |
Inner class of interface | InnerClassOfInterface |
Inner class too deeply nested | InnerClassTooDeeplyNested |
Insecure random number generation | UnsecureRandomNumberGeneration |
Inspection suppression annotation | SuppressionAnnotation |
Instance method naming convention | InstanceMethodNamingConvention |
Instance variable may not be initialized | InstanceVariableMayNotBeInitialized |
Instance variable may not be initialized by 'readObject()' | InstanceVariableMayNotBeInitializedByReadObject |
Instance variable naming convention | InstanceVariableNamingConvention |
Instance variable of concrete class | InstanceVariableOfConcreteClass |
Instance variable used before initialized | InstanceVariableUsedBeforeInitialized |
Instantiating a SimpleDateFormat without a Locale | SimpleDateFormatWithoutLocale |
Instantiating a Thread with default 'run()' method | InstantiatingAThreadWithDefaultRunMethod |
Instantiating object to get Class object | InstantiatingObjectToGetClassObject |
Instantiation of utility class | InstantiationOfUtilityClass |
Integer division in floating point context | IntegerDivisionInFloatingPointContext |
Integer multiplication or shift implicitly cast to long | IntegerMultiplicationImplicitCastToLong |
Interface naming convention | InterfaceNamingConvention |
Interface which has no concrete subclass | InterfaceNeverImplemented |
Interface which has only one direct inheritor | InterfaceWithOnlyOneDirectInheritor |
JDBC resource opened but not safely closed | JDBCResourceOpenedButNotSafelyClosed |
JNDI resource opened but not safely closed | JNDIResourceOpenedButNotSafelyClosed |
JUnit TestCase in product source | JUnitTestCaseInProductSource |
JUnit TestCase with non-trivial constructors | JUnitTestCaseWithNonTrivialConstructors |
JUnit abstract test class naming convention | JUnitAbstractTestClassNamingConvention |
JUnit test case with no tests | JUnitTestCaseWithNoTests |
JUnit test class naming convention | JUnitTestClassNamingConvention |
JUnit test method in product source | JUnitTestMethodInProductSource |
JUnit test method without any assertions | JUnitTestMethodWithNoAssertions |
Labeled statement | LabeledStatement |
Large array allocation with no OutOfMemoryError check | CheckForOutOfMemoryOnLargeArrayAllocation |
Limited-scope inner class | LimitedScopeInnerClass |
Local variable hides member variable | LocalVariableHidesMemberVariable |
Local variable naming convention | LocalVariableNamingConvention |
Local variable of concrete class | LocalVariableOfConcreteClass |
Local variable used and declared in different 'switch' branches | LocalVariableUsedAndDeclaredInDifferentSwitchBranches |
Lock acquired but not safely unlocked | LockAcquiredButNotSafelyReleased |
Long literal ending with 'l' instead of 'L' | LongLiteralEndingWithLowercaseL |
Loop statement that does not loop | LoopStatementThatDoesntLoop |
Loop variable not updated inside loop | LoopConditionNotUpdatedInsideLoop |
Loop with implicit termination condition | LoopWithImplicitTerminationCondition |
Malformed @Before or @After method | BeforeOrAfterWithIncorrectSignature |
Malformed @BeforeClass or @AfterClass method | BeforeOrAfterWithIncorrectSignature |
Malformed XPath expression | MalformedXPath |
Malformed format string | MalformedFormatString |
Malformed regular expression | MalformedRegex |
Manual array copy | ManualArrayCopy |
Manual array to collection copy | ManualArrayToCollectionCopy |
Map or Set may contain java.net.URL objects | CollectionContainsUrl |
Map replaceable by EnumMap | MapReplaceableByEnumMap |
Marker interface | MarkerInterface |
Message missing on JUnit assertion | MessageMissingOnJUnitAssertion |
Method call in loop condition | MethodCallInLoopCondition |
Method call violates Law of Demeter | LawOfDemeter |
Method is identical to its super method | RedundantMethodOverride |
Method may be 'static' | MethodMayBeStatic |
Method name same as class name | MethodNameSameAsClassName |
Method name same as parent class name | MethodNameSameAsParentName |
Method names differing only by case | MethodNamesDifferingOnlyByCase |
Method overloads method of superclass | MethodOverloadsMethodOfSuperclass |
Method overrides package local method of superclass located in other package | MethodOverridesPrivateMethodOfSuperclass |
Method overrides private method of superclass | MethodOverridesPrivateMethodOfSuperclass |
Method overrides static method of superclass | MethodOverridesStaticMethodOfSuperclass |
Method parameter naming convention | MethodParameterNamingConvention |
Method parameter of concrete class | MethodParameterOfConcreteClass |
Method return of concrete class | MethodReturnOfConcreteClass |
Method with more than three negations | MethodWithMoreThanThreeNegations |
Method with multiple loops | MethodWithMultipleLoops |
Method with multiple return points. | MethodWithMultipleReturnPoints |
Method with synchronized block could be synchronized method | MethodMayBeSynchronized |
Method with too many exceptions declared | MethodWithTooExceptionsDeclared |
Method with too many parameters | MethodWithTooManyParameters |
Mismatched query and update of collection | MismatchedQueryAndUpdateOfCollection |
Mismatched read and write of array | MismatchedReadAndWriteOfArray |
Misordered 'assertEquals()' parameters | MisorderedAssertEqualsParameters |
Missing @Deprecated annotation | MissingDeprecatedAnnotation |
Missing @Override annotation | override |
Missorted modifers | MissortedModifiers |
Multiple top level classes in single file | MultipleTopLevelClassesInFile |
Multiple variables in one declaration | MultipleVariablesInDeclaration |
Multiply or divide by power of two | MultiplyOrDivideByPowerOfTwo |
Native method | NativeMethod |
Nested 'switch' statement | NestedSwitchStatement |
Nested 'synchronized' statement | NestedSynchronizedStatement |
Nested 'try' statement | NestedTryStatement |
Nested assignment | NestedAssignment |
Nested conditional expression | NestedConditionalExpression |
Nested method call | NestedMethodCall |
No-op method in abstract class | NoopMethodInAbstractClass |
Non-boolean method name must not start with question word | NonBooleanMethodNameMayNotStartWithQuestion |
Non-constant String should be StringBuffer | NonConstantStringShouldBeStringBuffer |
Non-constant field with upper-case name | NonConstantFieldWithUpperCaseName |
Non-constant logger | NonConstantLogger |
Non-exception class name ends with 'Exception' | NonExceptionNameEndsWithException |
Non-final 'clone()' in secure context | NonFinalClone |
Non-final field of exception class | NonFinalFieldOfException |
Non-final field referenced in 'compareTo()' | CompareToUsesNonFinalVariable |
Non-final field referenced in 'equals()' | NonFinalFieldReferenceInEquals |
Non-final field referenced in 'hashCode()' | NonFinalFieldReferencedInHashCode |
Non-final static variable is used during class initialization | NonFinalStaticVariableUsedInClassInitialization |
Non-private field accessed in synchronized context | NonPrivateFieldAccessedInSynchronizedContext |
Non-reproducible call to java.lang.Math | NonReproducibleMathCall |
Non-serializable class with 'readObject()' or 'writeObject()' | NonSerializableClassWithSerializationMethods |
Non-serializable class with 'serialVersionUID' | NonSerializableClassWithSerialVersionUID |
Non-serializable field in a Serializable class | NonSerializableFieldInSerializableClass |
Non-serializable object bound to HttpSession | NonSerializableObjectBoundToHttpSession |
Non-serializable object passed to ObjectOutputStream | NonSerializableObjectPassedToObjectStream |
Non-short-circuit boolean expression | NonShortCircuitBooleanExpression |
Non-static initializer | NonStaticInitializer |
Non-static inner class in secure context | NonStaticInnerClassInSecureContext |
Non-synchronized method overrides synchronized method | NonSynchronizedMethodOverridesSynchronizedMethod |
Number comparison using '==', instead of 'equals()' | NumberEquality |
Number constructor call with primitive argument | CachedNumberConstructorCall |
Numeric cast that loses precision | NumericCastThatLosesPrecision |
Object allocation in loop | ObjectAllocationInLoop |
Object comparison using ==, instead of 'equals()' | ObjectEquality |
Object.equals(null) | ObjectEqualsNull |
Octal and decimal integers in same array | OctalAndDecimalIntegersInSameArray |
Octal integer | OctalInteger |
Overloaded methods with same number of parameters | OverloadedMethodsWithSameNumberOfParameters |
Overloaded variable argument method | OverloadedVarargsMethod |
Overly broad 'catch' block | OverlyBroadCatchBlock |
Overly complex anonymous inner class | OverlyComplexAnonymousInnerClass |
Overly complex arithmetic expression | OverlyComplexArithmeticExpression |
Overly complex boolean expression | OverlyComplexBooleanExpression |
Overly complex class | OverlyComplexClass |
Overly complex method | OverlyComplexMethod |
Overly coupled class | OverlyCoupledClass |
Overly coupled method | OverlyCoupledMethod |
Overly large initializer for array of primitive type | OverlyLargePrimitiveArrayInitializer |
Overly long method | OverlyLongMethod |
Overly nested method | OverlyNestedMethod |
Overly-strong type cast | OverlyStrongTypeCast |
Overridable method call during object construction | OverridableMethodCallDuringObjectConstruction |
Overridden method call during object construction | OverriddenMethodCallDuringObjectConstruction |
Package-visible field | PackageVisibleField |
Package-visible inner class | PackageVisibleInnerClass |
Parameter hides member variable | ParameterHidesMemberVariable |
Parameter name differs from parameter in overridden method | ParameterNameDiffersFromOverriddenParameter |
Pointless 'indexOf()' comparison | PointlessIndexOfComparison |
Pointless arithmetic expression | PointlessArithmeticExpression |
Pointless bitwise expression | PointlessBitwiseExpression |
Pointless boolean expression | PointlessBooleanExpression |
Private member access between outer and inner classes | PrivateMemberAccessBetweenOuterAndInnerClass |
Private method only used from inner class | MethodOnlyUsedFromInnerClass |
Prohibited exception caught | ProhibitedExceptionCaught |
Prohibited exception declared | ProhibitedExceptionDeclared |
Prohibited exception thrown | ProhibitedExceptionThrown |
Protected field | ProtectedField |
Protected inner class | ProtectedInnerClass |
Public field | PublicField |
Public inner class | PublicInnerClass |
Public method not exposed in interface | PublicMethodNotExposedInInterface |
Public method without logging | PublicMethodWithoutLogging |
Public static array field | PublicStaticArrayField |
Public static collection field | PublicStaticCollectionField |
Questionable name | QuestionableName |
Raw use of parameterized class | RawUseOfParameterizedType |
RecordStore opened but not safely closed | RecordStoreOpenedButNotSafelyClosed |
Redundant '.substring(0)' | SubstringZero |
Redundant 'String.toString()' | RedundantStringToString |
Redundant 'if' statement | RedundantIfStatement |
Redundant String constructor call | RedundantStringConstructorCall |
Redundant conditional expression | RedundantConditionalExpression |
Redundant field initialization | RedundantFieldInitialization |
Redundant import | RedundantImport |
Redundant interface declaration | RedundantInterfaceDeclaration |
Redundant local variable | UnnecessaryLocalVariable |
Redundant no-arg constructor | RedundantNoArgConstructor |
Reflective access to a source-only annotation | ReflectionForUnavailableAnnotation |
Refused bequest | RefusedBequest |
Result of method call ignored | ResultOfMethodCallIgnored |
Result of object allocation ignored | ResultOfObjectAllocationIgnored |
Return of 'null' | ReturnOfNull |
Return of 'this' | ReturnOfThis |
Return of Collection or array field | ReturnOfCollectionOrArrayField |
Return of Date or Calendar field | ReturnOfDateField |
Reuse of local variable | ReuseOfLocalVariable |
Scope of variable is too broad | TooBroadScope |
Serializable class in secure context | SerializableClassInSecureContext |
Serializable class with unconstructable ancestor | SerializableClassWithUnconstructableAncestor |
Serializable class without 'readObject()' and 'writeObject()' | SerializableHasSerializationMethods |
Serializable class without 'serialVersionUID' | serial |
Serializable non-static inner class with non-Serializable outer class | SerializableInnerClassWithNonSerializableOuterClass |
Serializable non-static inner class without 'serialVersionUID' | SerializableNonStaticInnerClassWithoutSerialVersionUID |
Set replaceable by EnumSet | SetReplaceableByEnumSet |
Shift operation by inappropriate constant | ShiftOutOfRange |
Simplifiable JUnit assertion | SimplifiableJUnitAssertion |
Single character 'startsWith()' or 'endsWith()' | SingleCharacterStartsWith |
Single character string concatenation | SingleCharacterStringConcatenation |
Single character string parameter in 'String.indexOf()' call | SingleCharacterStringConcatenation |
Single class import | SingleClassImport |
Singleton | Singleton |
Socket opened but not safely closed | SocketOpenedButNotSafelyClosed |
Standard variable names | StandardVariableNames |
Statement with empty body | StatementWithEmptyBody |
Static collection | StaticCollection |
Static field referenced via subclass | StaticFieldReferencedViaSubclass |
Static import | StaticImport |
Static inheritance | StaticInheritance |
Static method naming convention | StaticMethodNamingConvention |
Static method only used from one other class | StaticMethodOnlyUsedInOneClass |
Static method referenced via subclass | StaticMethodReferencedViaSubclass |
Static variable may not be initialized | StaticVariableMayNotBeInitialized |
Static variable naming convention | StaticVariableNamingConvention |
Static variable of concrete class | StaticVariableOfConcreteClass |
Static variable used before initialization | StaticVariableUsedBeforeInitialization |
String comparison using '==', instead of 'equals()' | StringEquality |
String concatenation | StringConcatenation |
String concatenation in loop | StringContatenationInLoop |
String concatenation inside 'StringBuffer.append()' | StringConcatenationInsideStringBufferAppend |
StringBuffer constructor call with 'char' argument | NewStringBufferWithCharArgument |
StringBuffer field | StringBufferField |
StringBuffer or StringBuilder without initial capacity | StringBufferWithoutInitialCapacity |
Subtraction in compareTo() | SubtractionInCompareTo |
Suspicious 'Collections.toArray()' call | SuspiciousToArrayCall |
Suspicious 'System.arraycopy()' call | SuspiciousSystemArraycopy |
Suspicious indentation after control statement without braces | SuspiciousIndentAfterControlStatement |
Suspicious test for oddness | BadOddness |
Synchronization on 'this' | SynchronizeOnThis |
Synchronization on a Lock object | SynchroniziationOnLockObject |
Synchronization on a non-final field | SynchronizeOnNonFinalField |
Synchronization on an object initialized with a literal | SynchronizedOnLiteralObject |
TODO comment | TodoComment |
Tail recursion | TailRecursion |
Test method with incorrect signature | TestMethodWithIncorrectSignature |
Text label in 'switch' statement | TextLabelInSwitchStatement |
Throwable instance not thrown | ThrowableInstanceNeverThrown |
Transient field in non-serializable class | TransientFieldInNonSerializableClass |
Transient field is not initialized on deserialization | TransientFieldNotInitialized |
Type may be weakened | TypeMayBeWeakened |
Type parameter explicitly extends 'java.lang.Object' | TypeParameterExplicitlyExtendsObject |
Type parameter extends final class | TypeParameterExtendsFinalClass |
Type parameter hides visible type | TypeParameterHidesVisibleType |
Type parameter naming convention | TypeParameterNamingConvention |
Unary plus | UnaryPlus |
Unchecked exception class | UncheckedExceptionClass |
Unconditional 'wait()' call | UnconditionalWait |
Unconstructable JUnit TestCase | UnconstructableJUnitTestCase |
Unnecessarily qualified static usage | UnnecessarilyQualifiedStaticUsage |
Unnecessary 'continue' statement | UnnecessaryContinue |
Unnecessary 'default' for enum switch statement | UnnecessaryDefault |
Unnecessary 'final' for local variable | UnnecessaryFinalOnLocalVariable |
Unnecessary 'final' for method parameter | UnnecessaryFinalForMethodParameter |
Unnecessary 'return' statement | UnnecessaryReturnStatement |
Unnecessary 'this' qualifier | UnnecessaryThis |
Unnecessary boxing | UnnecessaryBoxing |
Unnecessary call to 'super()' | UnnecessaryCallToSuper |
Unnecessary code block | UnnecessaryCodeBlock |
Unnecessary enum modifier | UnnecessaryEnumModifier |
Unnecessary fully qualified name | UnnecessaryFullyQualifiedName |
Unnecessary interface modifier | UnnecessaryInterfaceModifier |
Unnecessary label on 'break' statement | UnnecessaryLabelOnBreakStatement |
Unnecessary label on 'continue' statement | UnnecessaryLabelOnContinueStatement |
Unnecessary parentheses | UnnecessaryParentheses |
Unnecessary qualifier for 'this' | UnnecessaryQualifierForThis |
Unnecessary semicolon | UnnecessarySemicolon |
Unnecessary temporary object in conversion from String | UnnecessaryTemporaryOnConversionFromString |
Unnecessary temporary object in conversion to String | UnnecessaryTemporaryOnConversionToString |
Unnecessary unary minus | UnnecessaryUnaryMinus |
Unnecessary unboxing | UnnecessaryUnboxing |
Unpredictable BigDecimal constructor call | UnpredictableBigDecimalConstructorCall |
Unqualified instance field access | UnqualifiedFieldAccess |
Unqualified static usage | UnqualifiedStaticUsage |
Unsafe lazy initialization of static field | NonThreadSafeLazyInitialization |
Unused 'catch' parameter | UnusedCatchParameter |
Unused import | UnusedImport |
Unused label | UnusedLabel |
Use of '$' in identifier | DollarSignInName |
Use of 'assert' as identifier | AssertAsIdentifier |
Use of 'enum' as identifier | EnumAsIdentifier |
Use of AWT peer class | UseOfAWTPeerClass |
Use of DriverManager to get JDBC connection | CallToDriverManagerGetConnection |
Use of Properties object as a Hashtable | UseOfPropertiesAsHashtable |
Use of StringTokenizer | UseOfStringTokenizer |
Use of System.out or System.err | UseOfSystemOutOrSystemErr |
Use of archaic system property accessors | UseOfArchaicSystemPropertyAccessors |
Use of concrete JDBC driver class | UseOfJDBCDriverClass |
Use of index 0 in JDBC ResultSet | UseOfIndexZeroInJDBCResultSet |
Use of java.lang.ProcessBuilder class | UseOfProcessBuilder |
Use of java.lang.reflect | JavaLangReflect |
Use of obsolete collection type | UseOfObsoleteCollectionType |
Use of sun.* classes | UseOfSunClasses |
Using 'Random.nextDouble()' to get random integer | UsingRandomNextDoubleForRandomInteger |
Utility class | UtilityClass |
Utility class with public constructor | UtilityClassWithPublicConstructor |
Utility class without private constructor | UtilityClassWithoutPrivateConstructor |
Value of ++ or -- used | ValueOfIncrementOrDecrementUsed |
Variable argument method | VariableArgumentMethod |
Variables of different types in one declaration | VariablesOfDifferentTypesInDeclaration |
Volatile array field | VolatileArrayField |
Volatile long or double field | VolatileLongOrDoubleField |
While loop spins on field | WhileLoopSpinsOnField |
Zero-length array allocation | ZeroLengthArrayAllocation |
expression.equals("literal") rather than "literal".equals(expression) | LiteralAsArgToStringEquals |
java.lang import | JavaLangImport |
java.lang.Error not rethrown | ErrorNotRethrown |
java.lang.ThreadDeath not rethrown | ThreadDeathNotRethrown |
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://jazzy.id.au/images/james3.jpg)
Copyright James Roper. Some rights reserved .
![suppresswarnings unchecked assignment w3docs logo](https://www.w3docs.com/build/images/logo-color-w3.png)
- Password Generator
- HTML Editor
- HTML Encoder
- JSON Beautifier
- CSS Beautifier
- Markdown Convertor
- Find the Closest Tailwind CSS Color
- Phrase encrypt / decrypt
- Browser Feature Detection
- Number convertor
- CSS Maker text shadow
- CSS Maker Text Rotation
- CSS Maker Out Line
- CSS Maker RGB Shadow
- CSS Maker Transform
- CSS Maker Font Face
- Color Picker
- Colors CMYK
- Color mixer
- Color Converter
- Color Contrast Analyzer
- Color Gradient
- String Length Calculator
- MD5 Hash Generator
- Sha256 Hash Generator
- String Reverse
- URL Encoder
- URL Decoder
- Base 64 Encoder
- Base 64 Decoder
- Extra Spaces Remover
- String to Lowercase
- String to Uppercase
- Word Count Calculator
- Empty Lines Remover
- HTML Tags Remover
- Binary to Hex
- Hex to Binary
- Rot13 Transform on a String
- String to Binary
- Duplicate Lines Remover
![](http://omraadeinfo.online/777/templates/cheerup1/res/banner1.gif)
How do I address unchecked cast warnings?
An unchecked cast warning in Java occurs when the compiler cannot verify that a cast is safe at compile time. This can happen when you are casting an object to a type that is not a supertype or subtype of the object's actual type.
To address an unchecked cast warning, you can either suppress the warning using the @SuppressWarnings("unchecked") annotation, or you can modify your code to ensure that the cast is safe.
To suppress the warning, you can add the @SuppressWarnings annotation to the method or block of code that contains the unchecked cast. For example:
To ensure that the cast is safe, you can modify your code to ensure that the object being cast is actually an instance of the target type. For example:
I hope this helps! Let me know if you have any questions.
Related Resources
- How do I read / convert an InputStream into a String in Java?
- How do I generate random integers within a specific range in Java?
- How do I efficiently iterate over each entry in a Java Map?
- How can I create a memory leak in Java?
- How do I convert a String to an int in Java?
- How do I call one constructor from another in Java?
- HTML Basics
- Javascript Basics
- TypeScript Basics
- React Basics
- Angular Basics
- Sass Basics
- Vue.js Basics
- Python Basics
- Java Basics
- NodeJS Basics
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Cast a raw map to a generic map using a method, cleanly and safely in a fail early manner
Casting , instanceof , and @SuppressWarnings("unchecked") are noisy. It would be nice to stuff them down into a method where they won't need to be looked at. CheckedCast.castToMapOf() is an attempt to do that.
castToMapOf() is making some assumptions:
- (1) The map can't be trusted to be homogeneous
- (2) Redesigning to avoid need for casting or instanceof is not viable
- (3) Ensuring type safety in an fail early manner is more important than the performance hit
- (4) Returning Map<String,String> is sufficient (rather than returning HashMap<String, String> )
- (5) The key and value type args are not generic (like HashMap<ArrayList<String>, String> )
(1), (2) and (3) are symptoms of my work environment, beyond my control. (4) and (5) are compromises I've made because I haven't found good ways to overcome them yet.
(4) Is difficult to overcome because even if a HashMap.class was passed into a Class<M> I haven't been able to figure out how to return a M<K, V> . So I return a Map<K, V> .
(5) Is probably an inherent limitation of using Class<T> . I'd love to hear alternative ideas.
Despite those limitations can you see any problems with this java 1.5 code? Am I making any assumptions I haven't identified? Is there a better way to do this? If I'm reinventing the wheel please point me to the wheel. :)
Usage code block:
Methods code block:
Some reading I found helpful:
Generic factory with unknown implementation classes
Generic And Parameterized Types
I'm also wondering if a TypeReference / super type tokens might help with (4) and (5) and be a better way to approach this problem. If you think so please post an example.
- 3 \$\begingroup\$ "(4) Returning Map<String,String> is sufficient (rather than returning HashMap<String, String> " This is usually expected, we should program to interfaces, not implementations. I will be quite concerned if there are methods expecting a HashMap instead of a Map ... \$\endgroup\$ – h.j.k. Sep 2, 2014 at 11:55
- \$\begingroup\$ @h.j.k. This is largely true. But I'm trying to make the casting method as ignorant of what's being cast as I can. I hate that it "knows" we're talking about a Map. I've love to get the casting method to where it only knows we're casting some generic "thing" that holds two other "things". Then I could also use it for Pair<T1,T2> and whatnot. \$\endgroup\$ – candied_orange Sep 5, 2014 at 2:49
- \$\begingroup\$ how do you define a Pair ? If it's really just something that holds two other "things", full stop, then you do realize the semantic differences between that and a Map hmms? (we can move this to a chat room if you want to) \$\endgroup\$ – h.j.k. Sep 5, 2014 at 5:47
- \$\begingroup\$ chat.stackexchange.com/rooms/16939/… \$\endgroup\$ – candied_orange Sep 5, 2014 at 6:27
You should really rewrite the main method as proper unit tests, with separate test cases, for example:
I added a helper method iterateMapKeysAsStrings to trigger ClassCastException after an unsafe cast.
For testing an invalid cast with castToMapOf , you don't need to save the result in a variable:
I couldn't improve the implementation of castToMapOf . I tried a few things, but they didn't work out. The unit tests helped a lot in this: you either get "all green" results, or if something fails, you can pinpoint the problem, without having to read everything including the successful cases.
In comments you wrote that you like the detailed text in the ClassCastException in the checkCast method. I don't really see how this message matters. I understand that if you "test" your code with your original main method, it's easy to read. But with unit tests you don't have to read at all. I think less code is generally better: you could use a shorter message with the LS variable, without the System.getProperty("line.separator") .
![suppresswarnings unchecked assignment janos's user avatar](https://i.sstatic.net/Hg2nO.jpg?s=64)
- 1 \$\begingroup\$ I avoided jUnit style so you wouldn't have to scroll down so much. Removing result causes silly compiler errors. I happen to like whitespace. Have anything else to offer? \$\endgroup\$ – candied_orange Sep 2, 2014 at 10:35
- 1 \$\begingroup\$ I believe @SuppressWarnings("unchecked") has to be either directly above a single variable or applied to the entire method. \$\endgroup\$ – Simon Forsberg Sep 2, 2014 at 11:48
- 2 \$\begingroup\$ Yes and it's considered very bad style to apply it to the entire method because it hides other warnings. Despite what my silly eclipse IDE likes to do for me when I click on warnings. \$\endgroup\$ – candied_orange Sep 2, 2014 at 13:19
- \$\begingroup\$ I removed the incorrect remarks and added some meat in the unit test cases. \$\endgroup\$ – janos Sep 2, 2014 at 18:34
- \$\begingroup\$ Is iterateMapKeysAsStrings() just supposed to show off the for loop? Or that you can return void? I don't see that you've changed castToMapOf() at all. \$\endgroup\$ – candied_orange Sep 3, 2014 at 0:55
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged java generics casting or ask your own question .
Hot network questions.
- Are there any jobs that are forbidden by law to convicted felons?
- Is it allowed to use patents for new inventions?
- How do I tell which kit lens option is more all-purpose?
- What is the point of triggering of a national snap election immediately after losing the EU elections?
- How to explain the late added verses like in Matthew 18:11?
- Accidentally punctured through aluminum frame with a screw tip - still safe? Repairable?
- Can someone explain the damage distrubution on this aircraft that flew through a hailstorm?
- How was damno derived from damnum?
- Universal PCB enclosure: what are these cylinders with holes for?
- Is it rational for heterosexuals to be proud that they were born heterosexual?
- Is there a phrase like "etymologically related" but for food?
- How to use Sum properly to avoid problems when the summating limits are undefined?
- Do we know how the SpaceX Starship stack handles engine shutdowns?
- How can I use a transistor to control the segments on this 7-segment display?
- Improvising if I don't hear anything in my "mind's ear"?
- Why do I get different results for the products of two identical expressions?
- It suggests vs It would suggest
- Why is "second" an adverb in "came a close second"?
- What happens when you target a dead creature with Scrying?
- A trigonometric equation: how hard could it be?
- I'm looking for a series where there was a civilization in the Mediterranean basin, which got destroyed by the Atlantic breaking in
- is_decimal Function Implementation in C++
- Preventing Javascript in a browser from connecting to servers
- A short story in French about furniture that leaves a mansion by itself, and comes back some time later
Java中@SuppressWarnings("unchecked")的作用
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://csdnimg.cn/release/blogv2/dist/pc/img/reprint.png)
简介: java.lang.SuppressWarnings 是 J2SE5.0 中标准的 Annotation 之一。可以标注在类、字段、方法、参数、构造方法,以及局部变量上。 作用: 告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。 使用: @SuppressWarnings(“”) @SuppressWarnings({}) @SuppressWarnings(value={}) 根据 sun 的官方文档描述: value - 将由编译器在注释的元素中取消显示的警告集。允许使用重复的名称。忽略第二个和后面出现的名称。出现未被识别的警告名 不是 错误:编译器必须忽略无法识别的所有警告名。但如果某个注释包含未被识别的警告名,那么编译器可以随意发出一个警告。
各编译器供应商应该将它们所支持的警告名连同注释类型一起记录。鼓励各供应商之间相互合作,确保在多个编译器中使用相同的名称。
@SuppressWarnings("unchecked")
告诉编译器忽略 unchecked 警告信息,如使用 List , ArrayList 等未进行参数化产生的警告信息。
@SuppressWarnings("serial")
如果编译器出现这样的警告信息: The serializable class WmailCalendar does notdeclare a static final serialVersionUID field of type long 使用这个注释将警告信息去掉。
@SuppressWarnings("deprecation")
如果使用了使用 @Deprecated 注释的方法,编译器将出现警告信息。 使用这个注释将警告信息去掉。
@SuppressWarnings("unchecked", "deprecation")
告诉编译器同时忽略 unchecked 和 deprecation 的警告信息。
@SuppressWarnings(value={"unchecked", "deprecation"})
等同于 @SuppressWarnings("unchecked", "deprecation")
编码时我们总会发现如下变量未被使用的警告提示:
上述代码编译通过且可以运行,但每行前面的 “ 感叹号 ” 就严重阻碍了我们判断该行是否设置的断点了。这时我们可以在方法前添加 @SuppressWarnings( "unused" ) 去除这些 “ 感叹号 ” 。
二、 @SuppressWarings 注解
作用:用于抑制编译器产生警告信息。
示例 1—— 抑制单类型的警告:
@SuppressWarnings( "unchecked" )
public void addItems(String item){
@SuppressWarnings( "rawtypes" )
List items = new ArrayList();
items.add(item);
示例 2—— 抑制多类型的警告:
@SuppressWarnings(value={ "unchecked" , "rawtypes" })
示例 3—— 抑制所有类型的警告:
@SuppressWarnings( "all" )
三、注解目标
通过 @SuppressWarnings 的源码可知,其注解目标为类、字段、函数、函数入参、构造函数和函数的局部变量。
而家建议注解应声明在最接近警告发生的位置。
四、抑制警告的关键字
|
|
all | to suppress all warnings(抑制所有警告) |
boxing | to suppress warnings relative to boxing/unboxing operations(要抑制与箱/非装箱操作相关的警告) |
cast | to suppress warnings relative to cast operations(为了抑制与强制转换操作相关的警告) |
dep-ann | to suppress warnings relative to deprecated annotation(要抑制相对于弃用注释的警告) |
deprecation | to suppress warnings relative to deprecation(要抑制相对于弃用的警告) |
fallthrough | to suppress warnings relative to missing breaks in switch statements(在switch语句中,抑制与缺失中断相关的警告) |
finally | to suppress warnings relative to finally block that don’t return(为了抑制警告,相对于最终阻止不返回的警告) |
hiding | to suppress warnings relative to locals that hide variable(为了抑制本地隐藏变量的警告) |
incomplete-switch | to suppress warnings relative to missing entries in a switch statement (enum case)(为了在switch语句(enum案例)中抑制相对于缺失条目的警告) |
nls | to suppress warnings relative to non-nls string literals(要抑制相对于非nls字符串字面量的警告) |
null | to suppress warnings relative to null analysis(为了抑制与null分析相关的警告) |
rawtypes | to suppress warnings relative to un-specific types when using generics on class params(在类params上使用泛型时,要抑制相对于非特异性类型的警告) |
restriction | to suppress warnings relative to usage of discouraged or forbidden references(禁止使用警告或禁止引用的警告) |
serial | to suppress warnings relative to missing serialVersionUID field for a serializable class(为了一个可串行化的类,为了抑制相对于缺失的serialVersionUID字段的警告) |
static-access | o suppress warnings relative to incorrect static access(o抑制与不正确的静态访问相关的警告) |
synthetic-access | to suppress warnings relative to unoptimized access from inner classes(相对于内部类的未优化访问,来抑制警告) |
unchecked | to suppress warnings relative to unchecked operations(相对于不受约束的操作,抑制警告) |
unqualified-field-access | to suppress warnings relative to field access unqualified(为了抑制与现场访问相关的警告) |
unused | to suppress warnings relative to unused code(抑制没有使用过代码的警告) |
五、 Java Lint 选项
1. lint 的含义
用于在编译程序的过程中,进行更细节的额外检查。
- javac 的标准选项和非标准选项
标准选项: 是指当前版本和未来版本中都支持的选项,如 -cp 和 -d 等。
非标准选项: 是指当前版本支持,但未来不一定支持的选项。通过 javac -X 查看当前版本支持的非标准选项。
3. 查看警告信息
默认情况下执行 javac 仅仅显示警告的扼要信息,也不过阻止编译过程。若想查看警告的详细信息,则需要执行 javac -Xlint:keyword 来编译源码了。
六、总结
现在再都不怕不知道设置断点没有咯!
尊重原创,转载请注明来自: http://www.cnblogs.com/fsjohnhuang/p/4040785.html
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://csdnimg.cn/release/blogv2/dist/pc/img/vip-limited-close-newWhite.png)
“相关推荐”对你有帮助么?
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://csdnimg.cn/release/blogv2/dist/pc/img/npsFeel1.png)
请填写红包祝福语或标题
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://csdnimg.cn/release/blogv2/dist/pc/img/guideRedReward02.png)
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://csdnimg.cn/release/blogv2/dist/pc/img/recharge.png)
Valid @SuppressWarnings Warning Names
Last updated: January 16, 2024
- Java Annotations
![suppresswarnings unchecked assignment announcement - icon](https://www.baeldung.com/wp-content/uploads/2022/04/announcement-icon.png)
Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$
>> GET ACCESS NOW
Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.
The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.
>> Learn more and deploy your first Spring Boot app to Azure.
And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:
>> Try out the Profiler
A quick guide to materially improve your tests with Junit 5:
Do JSON right with Jackson
Download the E-book
Get the most out of the Apache HTTP Client
Get Started with Apache Maven:
Get started with Spring and Spring Boot, through the reference Learn Spring course:
>> LEARN SPRING
Building a REST API with Spring?
The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .
AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.
Simplify Your Coding Journey with Machinet AI :
>> Install Machinet AI in your IntelliJ
Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.
Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.
Write code that works the way you meant it to:
>> CodiumAI. Meaningful Code Tests for Busy Devs
Looking for the ideal Linux distro for running modern Spring apps in the cloud?
Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.
This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.
Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:
>> Try Alpaquita Containers now.
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .
You can explore the course here:
>> Learn Spring Security
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .
The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
>> Take a look at DBSchema
Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.
We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.
>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)
1. Overview
In this tutorial, we’ll take a look at the different warning names that work with the @SuppressWarnings Java annotation, which allows us to suppress compiler warnings. These warning names allow us to suppress particular warnings. The warning names available will depend on our IDE or Java compiler. The Eclipse IDE is our reference for this article.
2. Warning Names
Below is a list of valid warning names available in the @SuppressWarnings annotation:
- all : this is sort of a wildcard that suppresses all warnings
- boxing : suppresses warnings related to boxing/unboxing operations
- unused : suppresses warnings of unused code
- cast : suppresses warnings related to object cast operations
- deprecation : suppresses warnings related to deprecation, such as a deprecated class or method
- restriction : suppresses warnings related to the usage of discouraged or forbidden references
- dep-ann : suppresses warnings relative to deprecated annotations
- fallthrough : suppresses warnings related to missing break statements in switch statements
- finally : suppresses warnings related to finally blocks that don’t return
- hiding : suppresses warnings relative to locals that hide variables
- incomplete-switch : suppresses warnings relative to missing entries in a switch statement ( enum case)
- nls : suppresses warnings related to non-nls string literals
- null : suppresses warnings related to null analysis
- serial : suppresses warnings related to the missing serialVersionUID field, which is typically found in a Serializable class
- static-access : suppresses warnings related to incorrect static variable access
- synthetic-access : suppresses warnings related to unoptimized access from inner classes
- unchecked : suppresses warnings related to unchecked operations
- unqualified-field-access : suppresses warnings related to unqualified field access
- javadoc : suppresses warnings related to Javadoc
- rawtypes : suppresses warnings related to the usage of raw types
- resource : suppresses warnings related to the usage of resources of type Closeable
- super : suppresses warnings related to overriding a method without super invocations
- sync-override : suppresses warnings due to missing synchronize when overriding a synchronized method
3. Using Warning Names
This section will show examples of the use of different warning names.
3.1. @SuppressWarnings(“unused”)
In the example below, the warning name suppresses the warning of the unusedVal in the method:
3.2. @SuppressWarnings(“deprecation”)
In the example below, the warning name suppresses the warning of the usage of the @deprecated method:
3.3. @SuppressWarnings(“fallthrough”)
In the example below, the warning name suppresses the warning of the missing break statements — we’ve included them here, commented out, to show where we would otherwise get the warning:
3.4. @SuppressWarnings(“serial”)
This warning name is placed at the class level. In the example below, the warning name suppresses the warning of the missing serialVersionUID (which we’ve commented out) in a Serializable class:
4. Combining Multiple Warning Names
The @SuppressWarnings annotation expects an array of String s, so we can combine multiple warning names:
5. Conclusion
This article provides a list of valid @SuppressWarnings warning names. As usual, all code samples shown in this tutorial are available over on GitHub .
Slow MySQL query performance is all too common. Of course it is.
The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.
Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:
Basically, write code that works the way you meant it to.
AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
Get started with Spring Boot and with core Spring, through the Learn Spring course:
>> CHECK OUT THE COURSE
![suppresswarnings unchecked assignment Build your API with SPRING - book cover](https://www.baeldung.com/wp-content/uploads/2016/05/baeldung-rest-post-footer-main-1.2.0.jpg)
Follow the Java Category
![suppresswarnings unchecked assignment suppresswarnings unchecked assignment](https://www.baeldung.com/wp-content/uploads/2017/07/follow-the-spring.png)
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- Labs The future of collective knowledge sharing
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
How to remove unchecked assignment warning in hibernate generics
I am implementing the generics to access the data in hibernate using following code:
But at the line data = cr.list(); unchecked assignment warning is shown. How remove this warning without suppress warning ? If I change the return type from generic list to list then warning is removed but in that case I get the warning in class from where calling this method.
- You can put @SuppressWarnings("unchecked") above your get() method. But keep in mind if there is a warning, you may very well have an error at runtime. So really your question is twofold: how to disable the warning, and how to cope with the potential ensuing error. – Tim Biegeleisen Dec 24, 2015 at 4:21
- @Tim Biegeleisen thanks for reply but I don't want to suppress warning I want to handle it with my code implementation. Is there is any other way so I can implement this method without warning? – anand mishra Dec 24, 2015 at 4:25
- 1 If you want to do that, you need to have a proper generic type for everything you mention in your method, including Map , Iterator , and Map.Entry . – Louis Wasserman Dec 24, 2015 at 4:27
- @LouisWasserman thanks. But here map and iterator is used only for set criteria and restriction then how it will affect the return type of cr.list() ? – anand mishra Dec 24, 2015 at 4:36
Firstly, there are some problems in your code
- You don't commit and rollback a transaction.
- You don't need to log an exception in a low level method, just rethrow it.
If you log an exception you should do it this way
logger.debug("Hibernate Error", e);
You should rethrow an exception this way
throw new GenericDataAccessException(e);
You don't need data just do
return cr.list();
There is no way to remove an "unchecked assignment" warning, because of Criteria has a list() declaration with return type List not List<?> .
So just use suggested by @TimBiegeleisen @SuppressWarnings("unchecked") . But only in one low level place! Not above all kinds of get() methods. So you need to have a more complex architecture of your generics with one get() method.
Firstly, you can separate working with a session and transactions in the separate utility method. Something like this HibernateSessionFactory#doInTransaction() .
The second step is configure request parameters outside a request method (something likes your map ) like this HibernateRequest#list() .
![suppresswarnings unchecked assignment v.ladynev's user avatar](https://i.sstatic.net/nIUrV.jpg?s=64)
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged java hibernate generics or ask your own question .
- Featured on Meta
- The 2024 Developer Survey Is Live
- The return of Staging Ground to Stack Overflow
- The [tax] tag is being burninated
- Policy: Generative AI (e.g., ChatGPT) is banned
Hot Network Questions
- How do Authenticators work?
- Are there any jobs that are forbidden by law to convicted felons?
- The symmetry of multiplications with the number 9
- Who would I call to inspect the integrity of a truss after an electrician cut into it?
- Movie I saw in the 80s where a substance oozed off of movie stairs leaving a wet cat behind
- Find characters common among all strings
- Problems with coloured tables with \multirow and \multicolumn and text-wrapping for table with a lot of text. Getting blank, white areas
- Resolving conflicts
- Am I seeing double? What kind of helicopter is this, and how many blades does it actually have?
- My players think they found a loophole that gives them infinite poison and XP. How can I add the proper challenges to slow them down?
- Is the barrier to entry for mathematics research increasing, and is it at risk of becoming less accessible in the future?
- What does "far right tilt" actually mean in the context of the EU in 2024?
- What's the maximum amount of material that a puzzle with unique solution can have?
- Draw Memory Map/Layout/Region in TikZ
- Wifi deteriorates over time; cronjob to restart network manager
- When was the last time the G7 invited many guest countries?
- Customary learning areas for Shavuos?
- Smallest Harmonic number greater than N
- How to use Sum properly to avoid problems when the summating limits are undefined?
- Sum of square roots (as an algebraic number)
- Preventing Javascript in a browser from connecting to servers
- What do humans do uniquely, that computers apparently will not be able to?
- How can I use a router without gateway?
- What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
![](http://omraadeinfo.online/777/templates/cheerup1/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
@SuppressWarnings("unchecked") public List<User> findAllUsers(){ Query query = entitymanager.createQuery("SELECT u FROM User u"); return (List<User>)query.getResultList(); } If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList. In shortcut type-safety means: A ...
If you don't want the SuppressWarnings on an entire method, Java forces you to put it on a local. If you need a cast on a member it can lead to code like this: @SuppressWarnings("unchecked") Vector<String> watchedSymbolsClone = (Vector<String>) watchedSymbols.clone(); this.watchedSymbols = watchedSymbolsClone;
5.2. Checking Type Conversion Before Using the Raw Type Collection. The warning message " unchecked conversion " implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.
To suppress a list of multiple warnings, we set a String array containing the corresponding warning list: @SuppressWarnings({"unchecked", "deprecation"}) Copy. 3. Conclusion. In this guide, we saw how we can use the @SuppressWarnings annotation in Java. The full source code for the examples can be found over on GitHub.
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class. (All methods, variables, constructors).
The "unchecked cast" is a compile-time warning . Simply put, we'll see this warning when casting a raw type to a parameterized type without type checking. An example can explain it straightforwardly. Let's say we have a simple method to return a raw type Map: public class UncheckedCast {. public static Map getRawMap() {.
String [] value. The set of warnings that are to be suppressed by the compiler in the annotated element. Duplicate names are permitted. The second and successive occurrences of a name are ignored. The presence of unrecognized warning names is not an error: Compilers must ignore any warning names they do not recognize.
The set of warnings that are to be suppressed by the compiler in the annotated element. Duplicate names are permitted. The second and successive occurrences of a name are ignored. The presence of unrecognized warning names is not an error: Compilers must ignore any warning names they do not recognize. They are, however, free to emit a warning ...
@SuppressWarnings("unchecked") is an annotation in Java that tells the compiler to suppress specific warnings that are generated during the compilation of the code. The unchecked warning is issued by the compiler when a type safety check has been suppressed, typically using an @SuppressWarnings("unchecked") annotation or by using a raw type in a parameterized type.
1. In Class. If applied to class level, all the methods and members in this class will ignore the unchecked warnings message. @SuppressWarnings("unchecked") public class classA {...} 2. In Method. If applied to method level, only this method will ignore the unchecked warnings message.
In Java, the `@SuppressWarnings("unchecked")` annotation is used to inform the compiler to ignore unchecked warnings that occur when working with raw types in generics. These warnings are typically seen when the compiler encounters code where type safety cannot be guaranteed. Sometimes Java generics just doesn't allow certain operations without generating warnings.
@SuppressWarnings("unchecked") is sometimes correct and unavoidable in well-written code. Creating an array of generic types is one case. If you can work around it by using a Collection<T> or List<T> of generics then I'd suggest that, but if only an array will do, then there's nothing you can do.. Casting to a generic type is another similar case.
The unchecked assignment warning is a standard Java compiler warning. A quick Google will reveal that the name of the unchecked assignment warning to pass to @SuppressWarnings is "unchecked". IDE's however tend to flag warnings for much more than what the Java compiler flags warnings for. An example that I encountered today is in unit tests, if ...
An unchecked cast warning in Java occurs when the compiler cannot verify that a cast is safe at compile time. This can happen when you are casting an object to a type that is not a supertype or subtype of the object's actual type. To address an unchecked cast warning, you can either suppress the warning using the @SuppressWarnings("unchecked ...
Casting, instanceof, and @SuppressWarnings("unchecked") are noisy. It would be nice to stuff them down into a method where they won't need to be looked at. CheckedCast.castToMapOf() is an attempt to do that. castToMapOf() is making some assumptions: (1) The map can't be trusted to be homogeneous (2) Redesigning to avoid need for casting or instanceof is not viable
@SuppressWarnings("unchecked") static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) { return size -> (R[]) arrayCreator.apply(size); } This function converts the function to make an array of the raw type into a function that promises to make an array of the specific type we need: ... The unchecked assignment ...
293. It depends on your IDE or compiler. Here is a list for Eclipse Galileo: all to suppress all warnings. boxing to suppress warnings relative to boxing/unboxing operations. cast to suppress warnings relative to cast operations. dep-ann to suppress warnings relative to deprecated annotation. deprecation to suppress warnings relative to ...
Java中@SuppressWarnings("unchecked")的作用. 简介:java.lang.SuppressWarnings是J2SE5.0中标准的Annotation之一。. 可以标注在类、字段、方法、参数、构造方法,以及局部变量上。. 作用:告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。. value -将由编译器在注释 ...
The Venezuelan has tattoos associated with Tren de Aragua - which court documents for a suspected gang member in Georgia describe as five-pointed crowns, five-pointed stars and teardrops - the ...
Simply put @SuppressWarnings("unchecked") final T uncheckedXml = (T) xml; right before the assignment of res = uncheckedXml; for the "true" case, and similar for the second "else" one. - terrorrussia-keeps-killing
WASHINGTON — U.S. Senators Lindsey Graham (R-South Carolina) and Katie Britt (R-Alabama) yesterday commemorated the 80th anniversary of D-Day from Omaha Beach, one of five beach landing sites for the Allied forces during World War II. GRAHAM: "This was one of the most amazing experiences of my life. My dad was a World War II veteran in the Pacific in New Guinea. There were 66 ...
2. Warning Names. Below is a list of valid warning names available in the @SuppressWarnings annotation: all : this is sort of a wildcard that suppresses all warnings. boxing: suppresses warnings related to boxing/unboxing operations. unused: suppresses warnings of unused code. cast: suppresses warnings related to object cast operations.
1. Firstly, there are some problems in your code. You don't commit and rollback a transaction. You don't need to log an exception in a low level method, just rethrow it. If you log an exception you should do it this way. logger.debug("Hibernate Error", e); You should rethrow an exception this way.