• 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

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.

   

author

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

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.

Required Elements 
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

author image

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 🙂

java-json-tutorials

Java JSON Tutorials

Parsing JSON with Jackson, Moshi, Gson etc.

About Author

author image

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

Learn IT University

Learn IT University

Understanding the suppresswarnings(“unchecked”) annotation in java.

suppresswarnings unchecked assignment

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

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

Tagged in :

Andrii Piatakha Avatar

Andrii Piatakha

1 M Students Worldwide

Support me on Patreon and get access to exclusive content

Latest Posts

suppresswarnings unchecked assignment

Creating an Empty Stream in Java: A Step-by-Step Guide

suppresswarnings unchecked assignment

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

Community's user avatar

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.

John Kugelman's user avatar

  • 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):

user102008's user avatar

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?

suppresswarnings unchecked assignment

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 DescriptionWarning Name
"Magic character"MagicCharacter
"Magic number"MagicNumber
'Comparator.compare()' method does not use parameterComparatorMethodParameterNotUsed
'Connection.prepare*()' call with non-constant stringJDBCPrepareStatementWithNonConstantString
'Iterator.hasNext()' which calls 'next()'IteratorHasNextCallsIteratorNext
'Iterator.next()' which can't throw 'NoSuchElementException'IteratorNextCanNotThrowNoSuchElementException
'Statement.execute()' call with non-constant stringJDBCExecuteWithNonConstantString
'String.equals("")'StringEqualsEmptyString
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only)StringBufferMayBeStringBuilder
'StringBuffer.toString()' in concatenationStringBufferToStringInConcatenation
'assert' statementAssertStatement
'assertEquals()' between objects of inconvertible typesAssertEqualsBetweenInconvertibleTypes
'await()' not in loopAwaitNotInLoop
'await()' without corresponding 'signal()'AwaitWithoutCorrespondingSignal
'break' statementBreakStatement
'break' statement with labelBreakStatementWithLabel
'catch' generic classCatchGenericClass
'clone()' does not call 'super.clone()'CloneDoesntCallSuperClone
'clone()' does not declare 'CloneNotSupportedException'CloneDoesntDeclareCloneNotSupportedException
'clone()' instantiates objects with constructorCloneCallsConstructors
'clone()' method in non-Cloneable classCloneInNonCloneableClass
'compareto()' instead of 'compareTo()'MisspelledCompareTo
'continue' or 'break' inside 'finally' blockContinueOrBreakFromFinallyBlock
'continue' statementContinueStatement
'continue' statement with labelContinueStatementWithLabel
'default' not last case in 'switch'DefaultNotLastCaseInSwitch
'equal()' instead of 'equals()'MisspelledEquals
'equals()' between objects of inconvertible typesEqualsBetweenInconvertibleTypes
'equals()' called on array typeArrayEquals
'equals()' called on java.math.BigDecimalBigDecimalEquals
'equals()' method which does not check class of parameterEqualsWhichDoesntCheckParameterClass
'equals()' or 'hashCode()' called on java.net.URL objectEqualsHashCodeCalledOnUrl
'final' classFinalClass
'final' methodFinalMethod
'final' method in 'final' classFinalMethodInFinalClass
'finalize()' called explicitlyFinalizeCalledExplicitly
'finalize()' declarationFinalizeDeclaration
'finalize()' does not call 'super.finalize()'FinalizeDoesntCallSuperFinalize
'finalize()' not declared 'protected'FinalizeNotProtected
'finally' block which can not complete normallyfinally
'for' loop may be replaced by 'while' loopForLoopReplaceableByWhile
'for' loop replaceable by 'for each'ForLoopReplaceableByForEach
'for' loop where update or condition does not use loop variableForLoopThatDoesntUseLoopVariable
'for' loop with missing componentsForLoopWithMissingComponent
'hashcode()' instead of 'hashCode()'MisspelledHashcode
'if' statement with identical branchesIfStatementWithIdenticalBranches
'if' statement with negated conditionIfStatementWithNegatedCondition
'if' statement with too many branchesIfStatementWithTooManyBranches
'indexOf()' expression is replaceable by 'contains()'ListIndexOfReplaceableByContains
'instanceof' a concrete classInstanceofInterfaces
'instanceof' check for 'this'InstanceofThis
'instanceof' on 'catch' parameterInstanceofCatchParameter
'instanceof' with incompatible interfaceInstanceofIncompatibleInterface
'notify()' or 'notifyAll()' called on java.util.concurrent.locks.Condition objectNotifyCalledOnCondition
'notify()' or 'notifyAll()' while not syncedNotifyNotInSynchronizedContext
'notify()' or 'notifyAll()' without corresponding state changeNakedNotify
'notify()' without corresponding 'wait()'NotifyWithoutCorrespondingWait
'private' method declared 'final'FinalPrivateMethod
'protected' member in 'final' classProtectedMemberInFinalClass
'public' constructor in non-public classPublicConstructorInNonPublicClass
'readObject()' or 'writeObject()' not declared 'private'NonPrivateSerializationMethod
'readResolve()' or 'writeReplace()' not declared 'protected'ReadResolveAndWriteReplaceProtected
'return' inside 'finally' blockReturnInsideFinallyBlock
'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 signatureSetUpWithIncorrectSignature
'setup()' instead of 'setUp()'MisspelledSetUp
'signal()' without corresponding 'await()'SignalWithoutCorrespondingAwait
'size() == 0' replaceable by 'isEmpty()'SizeReplaceableByIsEmpty
'static' method declared 'final'FinalStaticMethod
'static', non-'final' fieldStaticNonFinalField
'suite()' method not declared 'static'SuiteNotDeclaredStatic
'switch' statementSwitchStatement
'switch' statement with too few branchesSwitchStatementWithTooFewBranches
'switch' statement with too low of a branch densitySwitchStatementDensity
'switch' statement with too many branchesSwitchStatementWithTooManyBranches
'switch' statement without 'default' branchSwitchStatementWithoutDefaultBranch
'synchronized' methodSynchronizedMethod
'tearDown()' does not call 'super.tearDown()'TearDownDoesntCallSuperTearDown
'tearDown()' with incorrect signatureTearDownWithIncorrectSignature
'teardown()' instead of 'tearDown()'MisspelledTearDown
'this' reference escaped in object constructionThisEscapedInObjectConstruction
'throw' caught by containing 'try' statementThrowCaughtLocally
'throw' inside 'catch' block which ignores the caught exceptionThrowInsideCatchBlockWhichIgnoresCaughtException
'throw' inside 'finally' blockThrowFromFinallyBlock
'tostring()' instead of 'toString()'MisspelledToString
'wait()' called on java.util.concurrent.locks.Condition objectWaitCalledOnCondition
'wait()' not in loopWaitNotInLoop
'wait()' or 'await()' without timeoutWaitOrAwaitWithoutTimeout
'wait()' while holding two locksWaitWhileHoldingTwoLocks
'wait()' while not syncedWaitWhileNotSynced
'wait()' without corresponding 'notify()'WaitWithoutCorrespondingNotify
'while' loop replaceable by 'for each'WhileLoopReplaceableByForEach
* importOnDemandImport
Abstract class extends concrete classAbstractClassExtendsConcreteClass
Abstract class which has no concrete subclassAbstractClassNeverImplemented
Abstract class which has only one direct inheritorAbstractClassWithOnlyOneDirectInheritor
Abstract class without abstract methodsAbstractClassWithoutAbstractMethods
Abstract method call in constructorAbstractMethodCallInConstructor
Abstract method overrides abstract methodAbstractMethodOverridesAbstractMethod
Abstract method overrides concrete methodAbstractMethodOverridesConcreteMethod
Abstract method with missing implementationsAbstractMethodWithMissingImplementations
Access of system propertiesAccessOfSystemProperties
Access to non thread-safe static field from instanceAccessToNonThreadSafeStaticFieldFromInstance
Access to static field locked on instance dataAccessToStaticFieldLockedOnInstance
Accessing a non-public field of another objectAccessingNonPublicFieldOfAnotherObject
AnnotationAnnotation
Annotation classAnnotationClass
Annotation naming conventionAnnotationNamingConvention
Anonymous class variable hides variable in containing methodAnonymousClassVariableHidesContainingMethodVariable
Anonymous inner classAnonymousInnerClass
Anonymous inner class may be a named static inner classAnonymousInnerClassMayBeStatic
Anonymous inner class with too many methodsAnonymousInnerClassWithTooManyMethods
Arithmetic operation on volatile fieldArithmeticOnVolatileField
Array.length in loop conditionArrayLengthInLoopCondition
Assignment replaceable with operator assignmentAssignmentReplaceableWithOperatorAssignment
Assignment to 'for' loop parameterAssignmentToForLoopParameter
Assignment to 'null'AssignmentToNull
Assignment to Collection or array field from parameterAssignmentToCollectionOrArrayFieldFromParameter
Assignment to Date or Calendar field from parameterAssignmentToDateFieldFromParameter
Assignment to catch block parameterAssignmentToCatchBlockParameter
Assignment to method parameterAssignmentToMethodParameter
Assignment to static field from instance methodAssignmentToStaticFieldFromInstanceMethod
Assignment used as conditionAssignmentUsedAsCondition
Auto-boxingAutoBoxing
Auto-unboxingAutoUnboxing
Boolean constructor callBooleanConstructorCall
Boolean method name must start with question wordBooleanMethodNameMustStartWithQuestion
Busy waitBusyWait
C-style array declarationCStyleArrayDeclaration
Call to 'Collection.toArray()' with zero-length array argumentToArrayCallWithZeroLengthArrayArgument
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 LocaleStringToUpperCaseOrToLowerCaseWithoutLocale
Call to 'System.exit()' or related methodsCallToSystemExit
Call to 'System.getenv()'CallToSystemGetenv
Call to 'System.loadLibrary()' with non-constant stringLoadLibraryWithNonConstantString
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 synchronizedSleepWhileHoldingLock
Call to 'Thread.start()' during object constructionCallToThreadStartDuringObjectConstruction
Call to 'Thread.stop()', 'suspend()' or 'resume()'CallToThreadStopSuspendOrResumeManager
Call to 'Thread.yield()'CallToThreadYield
Call to 'Time.toString()'CallToTimeToString
Call to 'intern()' on String constantConstantStringIntern
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 lockedCallToNativeMethodWhileLocked
Call to default 'toString()'ObjectToString
Call to simple getter from within classCallToSimpleGetterFromWithinClass
Call to simple setter from within classCallToSimpleSetterFromWithinClass
Calls to 'System.gc()' or 'Runtime.gc()'CallToSystemGC
Cast conflicts with 'instanceof'CastConflictsWithInstanceof
Cast to a concrete classCastToConcreteClass
Casting to incompatible interfaceCastToIncompatibleInterface
Caught exception is immediately rethrownCaughtExceptionImmediatelyRethrown
Chain of 'instanceof' checksChainOfInstanceofChecks
Chained equality comparisonsChainedEqualityComparisons
Chained method callsChainedMethodCall
Channel opened but not safely closedChannelOpenedButNotSafelyClosed
Character comparisonCharacterComparison
Checked exception classCheckedExceptionClass
Class escapes defined scopeClassEscapesDefinedScope
Class explicitly extends a Collection classClassExtendsConcreteCollection
Class explicitly extends java.lang.ObjectClassExplicitlyExtendsObject
Class explicitly extends java.lang.ThreadClassExplicitlyExtendsThread
Class extends annotation interfaceClassExplicitlyAnnotation
Class extends utility classExtendsUtilityClass
Class may be interfaceClassMayBeInterface
Class name differs from file nameClassNameDiffersFromFileName
Class name prefixed with package nameClassNamePrefixedWithPackageName
Class name same as ancestor nameClassNameSameAsAncestorName
Class naming conventionClassNamingConvention
Class references one of its subclassesClassReferencesSubclass
Class too deep in inheritance treeClassTooDeepInInheritanceTree
Class with multiple loggersClassWithMultipleLoggers
Class with too many constructorsClassWithTooManyConstructors
Class with too many fieldsClassWithTooManyFields
Class with too many methodsClassWithTooManyMethods
Class without 'toString()'ClassWithoutToString
Class without constructorClassWithoutConstructor
Class without loggerClassWithoutLogger
Class without no-arg constructorClassWithoutNoArgConstructor
Class without package statementClassWithoutPackageStatement
ClassLoader instantiationClassLoaderInstantiation
Cloneable class in secure contextCloneableClassInSecureContext
Cloneable class without 'clone()'CloneableClassWithoutClone
Collection added to selfCollectionAddedToSelf
Collection declared by class, not interfaceCollectionDeclaredAsConcreteClass
Collection without initial capacityCollectionWithoutInitialCapacity
Comparable implemented but 'equals()' not overriddenComparableImplementedButEqualsNotOverridden
Comparator class not declared SerializableComparatorNotSerializable
Comparison of 'short' and 'char' valuesComparisonOfShortAndChar
Comparison to Double.NaN or Float.NaNComparisonToNaN
Concatenation with empty stringConcatenationWithEmptyString
Conditional expression (?:)ConditionalExpression
Conditional expression with identical branchesConditionalExpressionWithIdenticalBranches
Conditional expression with negated conditionConditionalExpressionWithNegatedCondition
Conditional that can be simplified to && or ||SimplifiableConditionalExpression
Confusing 'else' branchConfusingElseBranch
Confusing 'main()' methodConfusingMainMethod
Confusing 'null' argument to var-arg methodNullArgumentToVariableArgMethod
Confusing floating-point literalConfusingFloatingPointLiteral
Confusing octal escape sequenceConfusingOctalEscapeSequence
Confusing primitive array argument to var-arg methodPrimitiveArrayArgumentToVariableArgMethod
Connection opened but not safely closedConnectionOpenedButNotSafelyClosed
Constant StringBuffer may be StringStringBufferReplaceableByString
Constant call to java.lang.Math or StrictMathConstantMathCall
Constant conditional expressionConstantConditionalExpression
Constant declared in abstract classConstantDeclaredInAbstractClass
Constant declared in interfaceConstantDeclaredInInterface
Constant if statementConstantIfStatement
Constant naming conventionConstantNamingConvention
Constant on left side of comparisonConstantOnLeftSideOfComparison
Constant on right side of comparisonConstantOnRightSideOfComparison
Constructor not 'protected' in 'abstract' classConstructorNotProtectedInAbstractClass
Constructor with too many parametersConstructorWithTooManyParameters
Control flow statement without bracesControlFlowStatementWithoutBraces
Covariant 'compareTo()'CovariantCompareTo
Covariant 'equals()'CovariantEquals
Custom ClassLoaderCustomClassloader
Custom SecurityManagerCustomSecurityManager
Deserializable class in secure contextDeserializableClassInSecureContext
Design for extensionDesignForExtension
Division by zerodivzero
Double negationDoubleNegation
Double-checked lockingDoubleCheckedLocking
Duplicate condition in 'if' statementDuplicateCondition
Duplicate condition on '&&' or '||'DuplicateBooleanBranch
Empty 'catch' blockEmptyCatchBlock
Empty 'finally' blockEmptyFinallyBlock
Empty 'synchronized' statementEmptySynchronizedStatement
Empty 'try' blockEmptyTryBlock
Empty classEmptyClass
Empty class initializerEmptyClassInitializer
Enum 'switch' statement that misses caseEnumSwitchStatementWhichMissesCases
Enumerated classEnumClass
Enumerated class naming conventionEnumeratedClassNamingConvention
Enumerated constant naming conventionEnumeratedConstantNamingConvention
Enumeration can be iterationEnumerationCanBeIteration
Exception class name does not end with 'Exception'ExceptionClassNameDoesntEndWithException
Extended 'for' statementForeachStatement
Externalizable class with 'readObject()' or 'writeObject()'ExternalizableClassWithSerializationMethods
Fallthrough in 'switch' statementfallthrough
Feature envyFeatureEnvy
Field accessed in both synchronized and unsynchronized contextsFieldAccessedSynchronizedAndUnsynchronized
Field has setter but no getterFieldHasSetterButNoGetter
Field may be 'static'FieldMayBeStatic
Field name hides field in superclassFieldNameHidesFieldInSuperclass
Field repeatedly accessed in methodFieldRepeatedlyAccessedInMethod
Floating point equality comparisonFloatingPointEquality
Hardcoded file separatorHardcodedFileSeparator
Hardcoded line separatorHardcodedLineSeparator
Hibernate resource opened but not safely closedHibernateResourceOpenedButNotSafelyClosed
I/O resource opened but not safely closedIOResourceOpenedButNotSafelyClosed
If statement may be replaced by && or || expressionSimplifiableIfStatement
Implicit call to 'super()'ImplicitCallToSuper
Implicit call to array '.toString()'ImplicitArrayToString
Implicit numeric conversionImplicitNumericConversion
Import from same packageSamePackageImport
Incompatible bitwise mask operationIncompatibleBitwiseMaskOperation
Infinite loop statementInfiniteLoopStatement
Infinite recursionInfiniteRecursion
Inner class field hides outer class fieldInnerClassFieldHidesOuterClassField
Inner class may be 'static'InnerClassMayBeStatic
Inner class of interfaceInnerClassOfInterface
Inner class too deeply nestedInnerClassTooDeeplyNested
Insecure random number generationUnsecureRandomNumberGeneration
Inspection suppression annotationSuppressionAnnotation
Instance method naming conventionInstanceMethodNamingConvention
Instance variable may not be initializedInstanceVariableMayNotBeInitialized
Instance variable may not be initialized by 'readObject()'InstanceVariableMayNotBeInitializedByReadObject
Instance variable naming conventionInstanceVariableNamingConvention
Instance variable of concrete classInstanceVariableOfConcreteClass
Instance variable used before initializedInstanceVariableUsedBeforeInitialized
Instantiating a SimpleDateFormat without a LocaleSimpleDateFormatWithoutLocale
Instantiating a Thread with default 'run()' methodInstantiatingAThreadWithDefaultRunMethod
Instantiating object to get Class objectInstantiatingObjectToGetClassObject
Instantiation of utility classInstantiationOfUtilityClass
Integer division in floating point contextIntegerDivisionInFloatingPointContext
Integer multiplication or shift implicitly cast to longIntegerMultiplicationImplicitCastToLong
Interface naming conventionInterfaceNamingConvention
Interface which has no concrete subclassInterfaceNeverImplemented
Interface which has only one direct inheritorInterfaceWithOnlyOneDirectInheritor
JDBC resource opened but not safely closedJDBCResourceOpenedButNotSafelyClosed
JNDI resource opened but not safely closedJNDIResourceOpenedButNotSafelyClosed
JUnit TestCase in product sourceJUnitTestCaseInProductSource
JUnit TestCase with non-trivial constructorsJUnitTestCaseWithNonTrivialConstructors
JUnit abstract test class naming conventionJUnitAbstractTestClassNamingConvention
JUnit test case with no testsJUnitTestCaseWithNoTests
JUnit test class naming conventionJUnitTestClassNamingConvention
JUnit test method in product sourceJUnitTestMethodInProductSource
JUnit test method without any assertionsJUnitTestMethodWithNoAssertions
Labeled statementLabeledStatement
Large array allocation with no OutOfMemoryError checkCheckForOutOfMemoryOnLargeArrayAllocation
Limited-scope inner classLimitedScopeInnerClass
Local variable hides member variableLocalVariableHidesMemberVariable
Local variable naming conventionLocalVariableNamingConvention
Local variable of concrete classLocalVariableOfConcreteClass
Local variable used and declared in different 'switch' branchesLocalVariableUsedAndDeclaredInDifferentSwitchBranches
Lock acquired but not safely unlockedLockAcquiredButNotSafelyReleased
Long literal ending with 'l' instead of 'L'LongLiteralEndingWithLowercaseL
Loop statement that does not loopLoopStatementThatDoesntLoop
Loop variable not updated inside loopLoopConditionNotUpdatedInsideLoop
Loop with implicit termination conditionLoopWithImplicitTerminationCondition
Malformed @Before or @After methodBeforeOrAfterWithIncorrectSignature
Malformed @BeforeClass or @AfterClass methodBeforeOrAfterWithIncorrectSignature
Malformed XPath expressionMalformedXPath
Malformed format stringMalformedFormatString
Malformed regular expressionMalformedRegex
Manual array copyManualArrayCopy
Manual array to collection copyManualArrayToCollectionCopy
Map or Set may contain java.net.URL objectsCollectionContainsUrl
Map replaceable by EnumMapMapReplaceableByEnumMap
Marker interfaceMarkerInterface
Message missing on JUnit assertionMessageMissingOnJUnitAssertion
Method call in loop conditionMethodCallInLoopCondition
Method call violates Law of DemeterLawOfDemeter
Method is identical to its super methodRedundantMethodOverride
Method may be 'static'MethodMayBeStatic
Method name same as class nameMethodNameSameAsClassName
Method name same as parent class nameMethodNameSameAsParentName
Method names differing only by caseMethodNamesDifferingOnlyByCase
Method overloads method of superclassMethodOverloadsMethodOfSuperclass
Method overrides package local method of superclass located in other packageMethodOverridesPrivateMethodOfSuperclass
Method overrides private method of superclassMethodOverridesPrivateMethodOfSuperclass
Method overrides static method of superclassMethodOverridesStaticMethodOfSuperclass
Method parameter naming conventionMethodParameterNamingConvention
Method parameter of concrete classMethodParameterOfConcreteClass
Method return of concrete classMethodReturnOfConcreteClass
Method with more than three negationsMethodWithMoreThanThreeNegations
Method with multiple loopsMethodWithMultipleLoops
Method with multiple return points.MethodWithMultipleReturnPoints
Method with synchronized block could be synchronized methodMethodMayBeSynchronized
Method with too many exceptions declaredMethodWithTooExceptionsDeclared
Method with too many parametersMethodWithTooManyParameters
Mismatched query and update of collectionMismatchedQueryAndUpdateOfCollection
Mismatched read and write of arrayMismatchedReadAndWriteOfArray
Misordered 'assertEquals()' parametersMisorderedAssertEqualsParameters
Missing @Deprecated annotationMissingDeprecatedAnnotation
Missing @Override annotationoverride
Missorted modifersMissortedModifiers
Multiple top level classes in single fileMultipleTopLevelClassesInFile
Multiple variables in one declarationMultipleVariablesInDeclaration
Multiply or divide by power of twoMultiplyOrDivideByPowerOfTwo
Native methodNativeMethod
Nested 'switch' statementNestedSwitchStatement
Nested 'synchronized' statementNestedSynchronizedStatement
Nested 'try' statementNestedTryStatement
Nested assignmentNestedAssignment
Nested conditional expressionNestedConditionalExpression
Nested method callNestedMethodCall
No-op method in abstract classNoopMethodInAbstractClass
Non-boolean method name must not start with question wordNonBooleanMethodNameMayNotStartWithQuestion
Non-constant String should be StringBufferNonConstantStringShouldBeStringBuffer
Non-constant field with upper-case nameNonConstantFieldWithUpperCaseName
Non-constant loggerNonConstantLogger
Non-exception class name ends with 'Exception'NonExceptionNameEndsWithException
Non-final 'clone()' in secure contextNonFinalClone
Non-final field of exception classNonFinalFieldOfException
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 initializationNonFinalStaticVariableUsedInClassInitialization
Non-private field accessed in synchronized contextNonPrivateFieldAccessedInSynchronizedContext
Non-reproducible call to java.lang.MathNonReproducibleMathCall
Non-serializable class with 'readObject()' or 'writeObject()'NonSerializableClassWithSerializationMethods
Non-serializable class with 'serialVersionUID'NonSerializableClassWithSerialVersionUID
Non-serializable field in a Serializable classNonSerializableFieldInSerializableClass
Non-serializable object bound to HttpSessionNonSerializableObjectBoundToHttpSession
Non-serializable object passed to ObjectOutputStreamNonSerializableObjectPassedToObjectStream
Non-short-circuit boolean expressionNonShortCircuitBooleanExpression
Non-static initializerNonStaticInitializer
Non-static inner class in secure contextNonStaticInnerClassInSecureContext
Non-synchronized method overrides synchronized methodNonSynchronizedMethodOverridesSynchronizedMethod
Number comparison using '==', instead of 'equals()'NumberEquality
Number constructor call with primitive argumentCachedNumberConstructorCall
Numeric cast that loses precisionNumericCastThatLosesPrecision
Object allocation in loopObjectAllocationInLoop
Object comparison using ==, instead of 'equals()'ObjectEquality
Object.equals(null)ObjectEqualsNull
Octal and decimal integers in same arrayOctalAndDecimalIntegersInSameArray
Octal integerOctalInteger
Overloaded methods with same number of parametersOverloadedMethodsWithSameNumberOfParameters
Overloaded variable argument methodOverloadedVarargsMethod
Overly broad 'catch' blockOverlyBroadCatchBlock
Overly complex anonymous inner classOverlyComplexAnonymousInnerClass
Overly complex arithmetic expressionOverlyComplexArithmeticExpression
Overly complex boolean expressionOverlyComplexBooleanExpression
Overly complex classOverlyComplexClass
Overly complex methodOverlyComplexMethod
Overly coupled classOverlyCoupledClass
Overly coupled methodOverlyCoupledMethod
Overly large initializer for array of primitive typeOverlyLargePrimitiveArrayInitializer
Overly long methodOverlyLongMethod
Overly nested methodOverlyNestedMethod
Overly-strong type castOverlyStrongTypeCast
Overridable method call during object constructionOverridableMethodCallDuringObjectConstruction
Overridden method call during object constructionOverriddenMethodCallDuringObjectConstruction
Package-visible fieldPackageVisibleField
Package-visible inner classPackageVisibleInnerClass
Parameter hides member variableParameterHidesMemberVariable
Parameter name differs from parameter in overridden methodParameterNameDiffersFromOverriddenParameter
Pointless 'indexOf()' comparisonPointlessIndexOfComparison
Pointless arithmetic expressionPointlessArithmeticExpression
Pointless bitwise expressionPointlessBitwiseExpression
Pointless boolean expressionPointlessBooleanExpression
Private member access between outer and inner classesPrivateMemberAccessBetweenOuterAndInnerClass
Private method only used from inner classMethodOnlyUsedFromInnerClass
Prohibited exception caughtProhibitedExceptionCaught
Prohibited exception declaredProhibitedExceptionDeclared
Prohibited exception thrownProhibitedExceptionThrown
Protected fieldProtectedField
Protected inner classProtectedInnerClass
Public fieldPublicField
Public inner classPublicInnerClass
Public method not exposed in interfacePublicMethodNotExposedInInterface
Public method without loggingPublicMethodWithoutLogging
Public static array fieldPublicStaticArrayField
Public static collection fieldPublicStaticCollectionField
Questionable nameQuestionableName
Raw use of parameterized classRawUseOfParameterizedType
RecordStore opened but not safely closedRecordStoreOpenedButNotSafelyClosed
Redundant '.substring(0)'SubstringZero
Redundant 'String.toString()'RedundantStringToString
Redundant 'if' statementRedundantIfStatement
Redundant String constructor callRedundantStringConstructorCall
Redundant conditional expressionRedundantConditionalExpression
Redundant field initializationRedundantFieldInitialization
Redundant importRedundantImport
Redundant interface declarationRedundantInterfaceDeclaration
Redundant local variableUnnecessaryLocalVariable
Redundant no-arg constructorRedundantNoArgConstructor
Reflective access to a source-only annotationReflectionForUnavailableAnnotation
Refused bequestRefusedBequest
Result of method call ignoredResultOfMethodCallIgnored
Result of object allocation ignoredResultOfObjectAllocationIgnored
Return of 'null'ReturnOfNull
Return of 'this'ReturnOfThis
Return of Collection or array fieldReturnOfCollectionOrArrayField
Return of Date or Calendar fieldReturnOfDateField
Reuse of local variableReuseOfLocalVariable
Scope of variable is too broadTooBroadScope
Serializable class in secure contextSerializableClassInSecureContext
Serializable class with unconstructable ancestorSerializableClassWithUnconstructableAncestor
Serializable class without 'readObject()' and 'writeObject()'SerializableHasSerializationMethods
Serializable class without 'serialVersionUID'serial
Serializable non-static inner class with non-Serializable outer classSerializableInnerClassWithNonSerializableOuterClass
Serializable non-static inner class without 'serialVersionUID'SerializableNonStaticInnerClassWithoutSerialVersionUID
Set replaceable by EnumSetSetReplaceableByEnumSet
Shift operation by inappropriate constantShiftOutOfRange
Simplifiable JUnit assertionSimplifiableJUnitAssertion
Single character 'startsWith()' or 'endsWith()'SingleCharacterStartsWith
Single character string concatenationSingleCharacterStringConcatenation
Single character string parameter in 'String.indexOf()' callSingleCharacterStringConcatenation
Single class importSingleClassImport
SingletonSingleton
Socket opened but not safely closedSocketOpenedButNotSafelyClosed
Standard variable namesStandardVariableNames
Statement with empty bodyStatementWithEmptyBody
Static collectionStaticCollection
Static field referenced via subclassStaticFieldReferencedViaSubclass
Static importStaticImport
Static inheritanceStaticInheritance
Static method naming conventionStaticMethodNamingConvention
Static method only used from one other classStaticMethodOnlyUsedInOneClass
Static method referenced via subclassStaticMethodReferencedViaSubclass
Static variable may not be initializedStaticVariableMayNotBeInitialized
Static variable naming conventionStaticVariableNamingConvention
Static variable of concrete classStaticVariableOfConcreteClass
Static variable used before initializationStaticVariableUsedBeforeInitialization
String comparison using '==', instead of 'equals()'StringEquality
String concatenationStringConcatenation
String concatenation in loopStringContatenationInLoop
String concatenation inside 'StringBuffer.append()'StringConcatenationInsideStringBufferAppend
StringBuffer constructor call with 'char' argumentNewStringBufferWithCharArgument
StringBuffer fieldStringBufferField
StringBuffer or StringBuilder without initial capacityStringBufferWithoutInitialCapacity
Subtraction in compareTo()SubtractionInCompareTo
Suspicious 'Collections.toArray()' callSuspiciousToArrayCall
Suspicious 'System.arraycopy()' callSuspiciousSystemArraycopy
Suspicious indentation after control statement without bracesSuspiciousIndentAfterControlStatement
Suspicious test for oddnessBadOddness
Synchronization on 'this'SynchronizeOnThis
Synchronization on a Lock objectSynchroniziationOnLockObject
Synchronization on a non-final fieldSynchronizeOnNonFinalField
Synchronization on an object initialized with a literalSynchronizedOnLiteralObject
TODO commentTodoComment
Tail recursionTailRecursion
Test method with incorrect signatureTestMethodWithIncorrectSignature
Text label in 'switch' statementTextLabelInSwitchStatement
Throwable instance not thrownThrowableInstanceNeverThrown
Transient field in non-serializable classTransientFieldInNonSerializableClass
Transient field is not initialized on deserializationTransientFieldNotInitialized
Type may be weakenedTypeMayBeWeakened
Type parameter explicitly extends 'java.lang.Object'TypeParameterExplicitlyExtendsObject
Type parameter extends final classTypeParameterExtendsFinalClass
Type parameter hides visible typeTypeParameterHidesVisibleType
Type parameter naming conventionTypeParameterNamingConvention
Unary plusUnaryPlus
Unchecked exception classUncheckedExceptionClass
Unconditional 'wait()' callUnconditionalWait
Unconstructable JUnit TestCaseUnconstructableJUnitTestCase
Unnecessarily qualified static usageUnnecessarilyQualifiedStaticUsage
Unnecessary 'continue' statementUnnecessaryContinue
Unnecessary 'default' for enum switch statementUnnecessaryDefault
Unnecessary 'final' for local variableUnnecessaryFinalOnLocalVariable
Unnecessary 'final' for method parameterUnnecessaryFinalForMethodParameter
Unnecessary 'return' statementUnnecessaryReturnStatement
Unnecessary 'this' qualifierUnnecessaryThis
Unnecessary boxingUnnecessaryBoxing
Unnecessary call to 'super()'UnnecessaryCallToSuper
Unnecessary code blockUnnecessaryCodeBlock
Unnecessary enum modifierUnnecessaryEnumModifier
Unnecessary fully qualified nameUnnecessaryFullyQualifiedName
Unnecessary interface modifierUnnecessaryInterfaceModifier
Unnecessary label on 'break' statementUnnecessaryLabelOnBreakStatement
Unnecessary label on 'continue' statementUnnecessaryLabelOnContinueStatement
Unnecessary parenthesesUnnecessaryParentheses
Unnecessary qualifier for 'this'UnnecessaryQualifierForThis
Unnecessary semicolonUnnecessarySemicolon
Unnecessary temporary object in conversion from StringUnnecessaryTemporaryOnConversionFromString
Unnecessary temporary object in conversion to StringUnnecessaryTemporaryOnConversionToString
Unnecessary unary minusUnnecessaryUnaryMinus
Unnecessary unboxingUnnecessaryUnboxing
Unpredictable BigDecimal constructor callUnpredictableBigDecimalConstructorCall
Unqualified instance field accessUnqualifiedFieldAccess
Unqualified static usageUnqualifiedStaticUsage
Unsafe lazy initialization of static fieldNonThreadSafeLazyInitialization
Unused 'catch' parameterUnusedCatchParameter
Unused importUnusedImport
Unused labelUnusedLabel
Use of '$' in identifierDollarSignInName
Use of 'assert' as identifierAssertAsIdentifier
Use of 'enum' as identifierEnumAsIdentifier
Use of AWT peer classUseOfAWTPeerClass
Use of DriverManager to get JDBC connectionCallToDriverManagerGetConnection
Use of Properties object as a HashtableUseOfPropertiesAsHashtable
Use of StringTokenizerUseOfStringTokenizer
Use of System.out or System.errUseOfSystemOutOrSystemErr
Use of archaic system property accessorsUseOfArchaicSystemPropertyAccessors
Use of concrete JDBC driver classUseOfJDBCDriverClass
Use of index 0 in JDBC ResultSetUseOfIndexZeroInJDBCResultSet
Use of java.lang.ProcessBuilder classUseOfProcessBuilder
Use of java.lang.reflectJavaLangReflect
Use of obsolete collection typeUseOfObsoleteCollectionType
Use of sun.* classesUseOfSunClasses
Using 'Random.nextDouble()' to get random integerUsingRandomNextDoubleForRandomInteger
Utility classUtilityClass
Utility class with public constructorUtilityClassWithPublicConstructor
Utility class without private constructorUtilityClassWithoutPrivateConstructor
Value of ++ or -- usedValueOfIncrementOrDecrementUsed
Variable argument methodVariableArgumentMethod
Variables of different types in one declarationVariablesOfDifferentTypesInDeclaration
Volatile array fieldVolatileArrayField
Volatile long or double fieldVolatileLongOrDoubleField
While loop spins on fieldWhileLoopSpinsOnField
Zero-length array allocationZeroLengthArrayAllocation
expression.equals("literal") rather than "literal".equals(expression)LiteralAsArgToStringEquals
java.lang importJavaLangImport
java.lang.Error not rethrownErrorNotRethrown
java.lang.ThreadDeath not rethrownThreadDeathNotRethrown

suppresswarnings unchecked assignment

Copyright James Roper. Some rights reserved .

w3docs logo

  • 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

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.

Community's user avatar

  • 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") .

janos's user avatar

  • 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

suppresswarnings unchecked assignment

Java中@SuppressWarnings("unchecked")的作用

suppresswarnings unchecked assignment

简介: 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

请填写红包祝福语或标题

suppresswarnings unchecked assignment

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

suppresswarnings unchecked assignment

Valid @SuppressWarnings Warning Names

Last updated: January 16, 2024

suppresswarnings unchecked assignment

  • Java Annotations

announcement - icon

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

Build your API with SPRING - book cover

Follow the Java Category

suppresswarnings unchecked assignment

  • 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.

anand mishra's user avatar

  • 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() .

v.ladynev's user avatar

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?

suppresswarnings unchecked assignment

IMAGES

  1. Doc8.docx

    suppresswarnings unchecked assignment

  2. Java :What is SuppressWarnings ("unchecked") in Java?(5solutioN)

    suppresswarnings unchecked assignment

  3. @suppresswarnings ("Unchecked") @suppresswarnings ("Unchecked

    suppresswarnings unchecked assignment

  4. SuppressWarnings.docx

    suppresswarnings unchecked assignment

  5. Assignment2.java

    suppresswarnings unchecked assignment

  6. Suppress unchecked warnings on method calls in Java

    suppresswarnings unchecked assignment

VIDEO

  1. Unchecked & Unspoken: A Loss in the Banking Community

  2. R : R

  3. Unchecked Aggression Live(5/21/11)

  4. Disable dialogs while script is running in Photoshop

  5. 제네릭 타입 명시: 일반달력 일간 정보를 조회한다

  6. Java :What causes javac to issue the "uses unchecked or unsafe operations" warning(5solution)

COMMENTS

  1. What is SuppressWarnings ("unchecked") in Java?

    @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 ...

  2. How do I address unchecked cast warnings?

    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;

  3. Java Warning "unchecked conversion"

    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.

  4. Java @SuppressWarnings Annotation

    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.

  5. The @SuppressWarnings Annotation in Java

    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).

  6. Java Warning "Unchecked Cast"

    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() {.

  7. SuppressWarnings (Java SE 11 & JDK 11 )

    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.

  8. SuppressWarnings (Java Platform SE 8 )

    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 ...

  9. What is SuppressWarnings ("unchecked") in Java?

    @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.

  10. How to suppress unchecked warnings

    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.

  11. Understanding the SuppressWarnings("unchecked") Annotation in Java

    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.

  12. java

    @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.

  13. all that jazz

    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 ...

  14. 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 ...

  15. java

    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

  16. Creating a Generic Array in Java

    @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 ...

  17. What is the list of valid @SuppressWarnings warning names in Java?

    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 ...

  18. Java中@SuppressWarnings("unchecked")的作用

    Java中@SuppressWarnings("unchecked")的作用. 简介:java.lang.SuppressWarnings是J2SE5.0中标准的Annotation之一。. 可以标注在类、字段、方法、参数、构造方法,以及局部变量上。. 作用:告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。. value -将由编译器在注释 ...

  19. Tren de Aragua: The Venezuelan gang infiltrating the US

    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 ...

  20. java

    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

  21. ICYMI: Graham and Britt on Omaha Beach for the 80th Anniversary of D

    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 ...

  22. Valid @SuppressWarnings Warning Names

    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.

  23. How to remove unchecked assignment warning in hibernate generics

    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.