SpotBugs manual¶
This manual is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/1.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
The name FindBugs and the FindBugs logo are trademarked by the University of Maryland.
Indices and tables¶
Contents¶
ã¯ã˜ã‚ã«Â¶
SpotBugs ã¯ã€Java プãƒã‚°ãƒ©ãƒ ã®ä¸ã®ãƒã‚°ã‚’見ã¤ã‘るプãƒã‚°ãƒ©ãƒ ã§ã™ã€‚ã“ã®ãƒ—ãƒã‚°ãƒ©ãƒ ã¯ã€ã€Œãƒã‚° パターンã€ã®å®Ÿä¾‹ã‚’探ã—ã¾ã™ã€‚「ãƒã‚° パターンã€ã¨ã¯ã€ã‚¨ãƒ©ãƒ¼ã¨ãªã‚‹å¯èƒ½æ€§ã®é«˜ã„コードã®äº‹ä¾‹ã§ã™ã€‚
This document describes version 3.1.0-RC5 of SpotBugs. We are very interested in getting your feedback on SpotBugs. Please visit the SpotBugs web page for the latest information on SpotBugs, contact information, and support resources such as information about the SpotBugs GitHub organization.
å¿…è¦æ¡ä»¶Â¶
SpotBugs を使用ã™ã‚‹ã«ã¯ã€ Java ãƒãƒ¼ã‚¸ãƒ§ãƒ³ 1.8 以é™ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã¨äº’æ›æ€§ã®ã‚るランタイム環境ãŒå¿…è¦ã§ã™ã€‚SpotBugs ã¯ã€ãƒ—ラットフォームéžä¾å˜ã§ã‚り〠GNU/Linux 〠Windows 〠MacOS X プラットフォーム上ã§å‹•ä½œã™ã‚‹ã“ã¨ãŒçŸ¥ã‚‰ã‚Œã¦ã„ã¾ã™ã€‚
SpotBugs を使用ã™ã‚‹ãŸã‚ã«ã¯ã€å°‘ãªãã¨ã‚‚ 512 MB ã®ãƒ¡ãƒ¢ãƒªãŒå¿…è¦ã§ã™ã€‚巨大ãªãƒ—ãƒã‚¸ã‚§ã‚¯ãƒˆã‚’解æžã™ã‚‹ãŸã‚ã«ã¯ã€ãれより多ãã®ãƒ¡ãƒ¢ãƒªãŒå¿…è¦ã¨ã•ã‚Œã‚‹ã“ã¨ãŒã‚ã‚Šã¾ã™ã€‚
インストール¶
ã“ã®ç« ã§ã¯SpotBugsã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«æ–¹æ³•ã‚’説明ã—ã¾ã™ã€‚
é…布パッケージã®å±•é–‹Â¶
The easiest way to install SpotBugs is to download a binary distribution. Binary distributions are available in gzipped tar format and zip format. Once you have downloaded a binary distribution, extract it into a directory of your choice.
Extracting a gzipped tar format distribution:
$ gunzip -c spotbugs-3.1.0-RC5.tgz | tar xvf -
Extracting a zip format distribution:
C:\Software> unzip spotbugs-3.1.0-RC5.zip
Usually, extracting a binary distribution will create a directory ending in spotbugs-3.1.0-RC5
.
For example, if you extracted the binary distribution from the C:\Software directory
, then the SpotBugs software will be extracted into the directory C:\Software\spotbugs-3.1.0-RC5
.
This directory is the SpotBugs home directory.
We’ll refer to it as $SPOTBUGS_HOME
(or %SPOTBUGS_HOME%
for Windows) throughout this manual.
Running SpotBugs¶
SpotBugs has two user interfaces: a graphical user interface (GUI) and a command line user interface. This chapter describes how to run each of these user interfaces.
Quick Start¶
If you are running SpotBugs on a Windows system, double-click on the file %SPOTBUGS_HOME%\lib\spotbugs.jar
to start the SpotBugs GUI.
On a Unix, Linux, or macOS system, run the $SPOTBUGS_HOME/bin/spotbugs
script, or run the command java -jar $SPOTBUGS_HOME/lib/spotbugs.jar
to run the SpotBugs GUI.
Refer to Using the SpotBugs GUI for information on how to use the GUI.
Executing SpotBugs¶
This section describes how to invoke the SpotBugs program. There are two ways to invoke SpotBugs: directly, or using a wrapper script.
Direct invocation of SpotBugs¶
The preferred method of running SpotBugs is to directly execute $SPOTBUGS_HOME/lib/spotbugs.jar
using the -jar command line switch of the JVM (java) executable.
(Versions of SpotBugs prior to 1.3.5 required a wrapper script to invoke SpotBugs.)
The general syntax of invoking SpotBugs directly is the following:
java [JVM arguments] -jar $SPOTBUGS_HOME/lib/spotbugs.jar options...
Choosing the User Interface¶
The first command line option chooses the SpotBugs user interface to execute. Possible values are:
- -gui:
- runs the graphical user interface (GUI)
- -textui:
- runs the command line user interface
- -version:
- displays the SpotBugs version number
- -help:
- displays help information for the SpotBugs command line user interface
- -gui1:
- executes the original (obsolete) SpotBugs graphical user interface
Java Virtual Machine (JVM) arguments¶
Several Java Virtual Machine arguments are useful when invoking SpotBugs.
- -XmxNNm:
- Set the maximum Java heap size to NN megabytes. SpotBugs generally requires a large amount of memory. For a very large project, using 1500 megabytes is not unusual.
- -Dname=value:
- Set a Java system property.
For example, you might use the argument
-Duser.language=ja
to display GUI messages in Japanese.
Invocation of SpotBugs using a wrapper script¶
Another way to run SpotBugs is to use a wrapper script.
On Unix-like systems, use the following command to invoke the wrapper script:
$ $SPOTBUGS_HOME/bin/spotbugs options...
On Windows systems, the command to invoke the wrapper script is
C:\My Directory>%SPOTBUGS_HOME%\bin\spotbugs.bat options...
On both Unix-like and Windows systems, you can simply add the $SPOTBUGS_HOME/bin
directory to your PATH
environment variable and then invoke SpotBugs using the spotbugs
command.
Wrapper script command line options¶
The SpotBugs wrapper scripts support the following command-line options. Note that these command line options are not handled by the SpotBugs program per se; rather, they are handled by the wrapper script.
- -jvmArgs args:
Specifies arguments to pass to the JVM. For example, you might want to set a JVM property:
$ spotbugs -textui -jvmArgs "-Duser.language=ja" myApp.jar
- -javahome directory:
- Specifies the directory containing the JRE (Java Runtime Environment) to use to execute FindBugs.
- -maxHeap size:
- Specifies the maximum Java heap size in megabytes. The default is 256. More memory may be required to analyze very large programs or libraries.
- -debug:
- Prints a trace of detectors run and classes analyzed to standard output. Useful for troubleshooting unexpected analysis failures.
- -property name=value:
- This option sets a system property. SpotBugs uses system properties to configure analysis options. See Analysis Properties. You can use this option multiple times in order to set multiple properties. Note: In most versions of Windows, the name=value string must be in quotes.
Command-line Options¶
This section describes the command line options supported by SpotBugs. These command line options may be used when invoking SpotBugs directly, or when using a wrapper script.
Common command-line options¶
These options may be used with both the GUI and command-line interfaces.
- -effort:min:
- This option disables analyses that increase precision but also increase memory consumption. You may want to try this option if you find that SpotBugs runs out of memory, or takes an unusually long time to complete its analysis.
- -effort:max:
- Enable analyses which increase precision and find more bugs, but which may require more memory and take more time to complete.
- -project project:
- Specify a project to be analyzed. The project file you specify should be one that was created using the GUI interface. It will typically end in the extension .fb or .fbp.
GUI Options¶
These options are only accepted by the Graphical User Interface.
- -look:plastic|gtk|native:
- Set Swing look and feel.
Text UI Options¶
These options are only accepted by the Text User Interface.
- -sortByClass:
- Sort reported bug instances by class name.
- -include filterFile.xml:
- Only report bug instances that match the filter specified by filterFile.xml. See Filter file.
- -exclude filterFile.xml:
- Report all bug instances except those matching the filter specified by filterFile.xml. See Filter file.
- -onlyAnalyze com.foobar.MyClass,com.foobar.mypkg.*:
- Restrict analysis to find bugs to given comma-separated list of classes and packages. Unlike filtering, this option avoids running analysis on classes and packages that are not explicitly matched: for large projects, this may greatly reduce the amount of time needed to run the analysis. (However, some detectors may produce inaccurate results if they aren’t run on the entire application.) Classes should be specified using their full classnames (including package), and packages should be specified in the same way they would in a Java import statement to import all classes in the package (i.e., add .* to the full name of the package). Replace .* with .- to also analyze all subpackages.
- -low:
- Report all bugs.
- -medium:
- Report medium and high priority bugs. This is the default setting.
- -high:
- Report only high priority bugs.
- -relaxed:
- Relaxed reporting mode. For many detectors, this option suppresses the heuristics used to avoid reporting false positives.
- -xml:
- Produce the bug reports as XML.
The XML data produced may be viewed in the GUI at a later time.
You may also specify this option as
-xml:withMessages
; when this variant of the option is used, the XML output will contain human-readable messages describing the warnings contained in the file. XML files generated this way are easy to transform into reports. - -html:
Generate HTML output. By default, SpotBugs will use the default.xsl XSLT stylesheet to generate the HTML: you can find this file in spotbugs.jar, or in the SpotBugs source or binary distributions. Variants of this option include
-html:plain.xsl
,-html:fancy.xsl
and-html:fancy-hist.xsl
. Theplain.xsl
stylesheet does not use Javascript or DOM, and may work better with older web browsers, or for printing. Thefancy.xsl
stylesheet uses DOM and Javascript for navigation and CSS for visual presentation. Thefancy-hist.xsl
an evolution offancy.xsl
stylesheet. It makes an extensive use of DOM and Javascript for dynamically filtering the lists of bugs.If you want to specify your own XSLT stylesheet to perform the transformation to HTML, specify the option as
-html:myStylesheet.xsl
, wheremyStylesheet.xsl
is the filename of the stylesheet you want to use.- -emacs:
- Produce the bug reports in Emacs format.
- -xdocs:
- Produce the bug reports in xdoc XML format for use with Apache Maven.
- -output filename:
- Produce the output in the specified file.
- -outputFile filename:
- This argument is deprecated. Use
-output
instead. - -nested[:true|false]:
- This option enables or disables scanning of nested jar and zip files found in the list of files and directories to be analyzed.
By default, scanning of nested jar/zip files is enabled. To disable it, add
-nested:false
to the command line arguments. - -auxclasspath classpath:
- Set the auxiliary classpath for analysis. This classpath should include all jar files and directories containing classes that are part of the program being analyzed but you do not want to have analyzed for bugs.
- -auxclasspathFromInput:
- Read the auxiliary classpath for analysis from standard input, each line adds new entry to the auxiliary classpath for analysis.
- -auxclasspathFromFile filepath:
- Read the auxiliary classpath for analysis from file, each line adds new entry to the auxiliary classpath for analysis.
- -analyzeFromFile filepath:
- Read the files to analyze from file, each line adds new entry to the classpath for analysis.
- -userPrefs edu.umd.cs.findbugs.core.prefs:
- Set the path of the user preferences file to use, which might override some of the options above. Specifying userPrefs as first argument would mean some later options will override them, as last argument would mean they will override some previous options). This rationale behind this option is to reuse SpotBugs Eclipse project settings for command line execution.
Using the SpotBugs GUI¶
This chapter describes how to use the SpotBugs graphical user interface (GUI).
Creating a Project¶
After you have started SpotBugs using the spotbugs
command, choose the File → New Project
menu item.
You will see a dialog which looks like this:
Use the “Add” button next to “Classpath to analyze” to select a Java archive file (zip, jar, ear, or war file) or directory containing java classes to analyze for bugs. You may add multiple archives/directories.
You can also add the source directories which contain the source code for the Java archives you are analyzing. This will enable SpotBugs to highlight the source code which contains a possible error. The source directories you add should be the roots of the Java package hierarchy. For example, if your application is contained in the org.foobar.myapp
package, you should add the parent directory of the org directory to the source directory list for the project.
Another optional step is to add additional Jar files or directories as “Auxiliary classpath locations” entries. You should do this if the archives and directories you are analyzing have references to other classes which are not included in the analyzed archives/directories and are not in the standard runtime classpath. Some of the bug pattern detectors in FindBugs make use of class hierarchy information, so you will get more accurate results if the entire class hierarchy is available which FindBugs performs its analysis.
Running the Analysis¶
Once you have added all of the archives, directories, and source directories, click the “Analyze” button to analyze the classes contained in the Jar files. Note that for a very large program on an older computer, this may take quite a while (tens of minutes). A recent computer with ample memory will typically be able to analyze a large program in only a few minutes.
Browsing Results¶
When the analysis completes, you will see a screen like the following:
The upper left-hand pane of the window shows the bug tree; this is a hierarchical representation of all of the potential bugs detected in the analyzed Jar files.
When you select a particular bug instance in the top pane, you will see a description of the bug in the “Details” tab of the bottom pane. In addition, the source code pane on the upper-right will show the program source code where the potential bug occurs, if source is available. In the above example, the bug is a stream object that is not closed. The source code window highlights the line where the stream object is created.
You may add a textual annotations to bug instances. To do so, type them into the text box just below the hierarchical view. You can type any information which you would like to record. When you load and save bug results files, the annotations are preserved.
Saving and Opening¶
You may use the File → Save as...
menu option to save your work. To save your work, including the jar file lists you specified and all bug results, choose “FindBugs analysis results (.xml)” from the drop-down list in the “Save as...” dialog. There are also options for saving just the jar file lists (“FindBugs project file (.fbp)”) or just the results (“FindBugs analysis file (.fba)”). A saved file may be loaded with the File → Open...
menu option.
Using the SpotBugs Eclipse plugin¶
The SpotBugs Eclipse plugin allows SpotBugs to be used within the Eclipse IDE. The SpotBugs Eclipse plugin was generously contributed by Peter Friese. Phil Crosby and Andrey Loskutov contributed major improvements to the plugin.
Requirements¶
To use the SpotdBugs Plugin for Eclipse, you need Eclipse Neon (4.6) or later.
Installation¶
We provide update sites that allow you to automatically install SpotBugs into Eclipse and also query and install updates. There are three different update sites:
- https://spotbugs.github.io/eclipse/
- Only provides official releases of SpotBugs Eclipse plugin.
- https://spotbugs.github.io/eclipse-candidate/
- Provides official releases and release candidates of SpotBugs Eclipse plugin.
- https://spotbugs.github.io/eclipse-latest/
- Provides latest SpotBugs Eclipse plugin built from master branch.
Or just use Eclipse marketplace to install SpotBugs Eclipse plugin.
Using the Plugin¶
To get started, right click on a Java project in Package Explorer, and select the option labeled “Spot Bugs”. SpotBugs will run, and problem markers (displayed in source windows, and also in the Eclipse Problems view) will point to locations in your code which have been identified as potential instances of bug patterns.
You can also run SpotBugs on existing java archives (jar, ear, zip, war etc). Simply create an empty Java project and attach archives to the project classpath. Having that, you can now right click the archive node in Package Explorer and select the option labeled “Spot Bugs”. If you additionally configure the source code locations for the binaries, SpotBugs will also link the generated warnings to the right source files.
You may customize how SpotBugs runs by opening the Properties dialog for a Java project, and choosing the “SpotBugs” property page. Options you may choose include:
- Enable or disable the “Run SpotBugs Automatically” checkbox. When enabled, SpotBugs will run every time you modify a Java class within the project.
- Choose minimum warning priority and enabled bug categories. These options will choose which warnings are shown. For example, if you select the “Medium” warning priority, only Medium and High priority warnings will be shown. Similarly, if you uncheck the “Style” checkbox, no warnings in the Style category will be displayed.
- Select detectors. The table allows you to select which detectors you want to enable for your project.
Extending the Eclipse Plugin (since 2.0.0)¶
Eclipse plugin supports contribution of custom SpotBugs detectors (see also AddingDetectors.txt for more information). There are two ways to contribute custom plugins to the Eclipse:
Existing standard SpotBugs detector packages can be configured via
Window → Preferences → Java → FindBugs → Misc. Settings → Custom Detectors
. Simply specify there locations of any additional plugin libraries. The benefit of this solution is that already existing detector packages can be used “as is”, and that you can quickly verify the quality of third party detectors. The drawback is that you have to apply this settings in each new Eclipse workspace, and this settings can’t be shared between team members.It is possible to contribute custom detectors via standard Eclipse extensions mechanism.
Please check the documentation of the
eclipsePlugin/schema/detectorPlugins.exsd
extension point how to update the plugin.xml. Existing FindBugs detector plugins can be easily “extended” to be full featured SpotBugs AND Eclipse detector plugins. Usually you only need to addMETA-INF/MANIFEST.MF
andplugin.xml
to the jar and update your build scripts to not to override theMANIFEST.MF
during the build.The benefit of this solution is that for given (shared) Eclipse installation each team member has exactly same detectors set, and there is no need to configure anything anymore. The (really small) precondition is that you have to convert your existing detectors package to the valid Eclipse plugin. You can do this even for third-party detector packages. Another major differentiator is the ability to extend the default SpotBugs classpath at runtime with required third party libraries (see AddingDetectors.txt for more information).
Troubleshooting¶
This section lists common problems with the plugin and (if known) how to resolve them.
If you see OutOfMemory error dialogs after starting SpotBugs analysis in Eclipse, please increase JVM available memory: change
eclipse.ini
and add the lines below to the end of the file:-vmargs -Xmx1000m
Important: the configuration arguments starting with the line
-vmargs
must be last lines in theeclipse.ini
file, and only one argument per line is allowed!If you do not see any SpotBugs problem markers (in your source windows or in the Problems View), you may need to change your
Problems View
filter settings. See FAQ for more information.
Using the SpotBugs Ant task¶
This chapter describes how to integrate SpotBugs into a build script for Ant, which is a popular Java build and deployment tool. Using the SpotBugs Ant task, your build script can automatically run SpotBugs on your Java code.
The Ant task was generously contributed by Mike Fagan.
Installing the Ant task¶
To install the Ant task, simply copy $SPOTBUGS_HOME/lib/spotbugs-ant.jar
into the lib subdirectory of your Ant installation.
注釈
It is strongly recommended that you use the Ant task with the version of SpotBugs it was included with. We do not guarantee that the Ant task Jar file will work with any version of SpotBugs other than the one it was included with.
Modifying build.xml¶
To incorporate SpotBugs into build.xml (the build script for Ant), you first need to add a task definition. This should appear as follows:
<taskdef
resource="edu/umd/cs/findbugs/anttask/tasks.properties"
classpath="path/to/spotbugs-ant.jar" />
The task definition specifies that when a spotbugs element is seen in build.xml
, it should use the indicated class to execute the task.
After you have added the task definition, you can define a target which uses the spotbugs task.
Here is an example which could be added to the build.xml
for the Apache BCEL library.
<property name="spotbugs.home" value="/export/home/daveho/work/spotbugs" />
<target name="spotbugs" depends="jar">
<spotbugs home="${spotbugs.home}"
output="xml"
outputFile="bcel-sb.xml" >
<auxClasspath path="${basedir}/lib/Regex.jar" />
<sourcePath path="${basedir}/src/java" />
<class location="${basedir}/bin/bcel.jar" />
</spotbugs>
</target>
The spotbugs element must have the home attribute set to the directory in which SpotBugs is installed; in other words, $SPOTBUGS_HOME
. See インストール.
This target will execute SpotBugs on bcel.jar
, which is the Jar file produced by BCEL’s build script. (By making it depend on the “jar” target, we ensure that the library is fully compiled before running SpotBugs on it.)
The output of SpotBugs will be saved in XML format to a file called bcel-sb.xml
.
An auxiliary Jar file, Regex.jar, is added to the aux classpath, because it is referenced by the main BCEL library.
A source path is specified so that the saved bug data will have accurate references to the BCEL source code.
Executing the task¶
Here is an example of invoking Ant from the command line, using the spotbugs target defined above.
[daveho@noir]$ ant spotbugs
Buildfile: build.xml
init:
compile:
examples:
jar:
spotbugs:
[spotbugs] Running SpotBugs...
[spotbugs] Bugs were found
[spotbugs] Output saved to bcel-sb.xml
BUILD SUCCESSFUL
Total time: 35 seconds
In this case, because we saved the bug results in an XML file, we can use the SpotBugs GUI to view the results; see Running SpotBugs.
Parameters¶
This section describes the parameters that may be specified when using the FindBugs task.
- class
A optional nested element specifying which classes to analyze. The class element must specify a location attribute which names the archive file (jar, zip, etc.), directory, or class file to be analyzed. Multiple class elements may be specified as children of a single spotbugs element.
In addition to or instead of specifying a class element, the SpotBugs task can contain one or more fileset element(s) that specify files to be analyzed. For example, you might use a fileset to specify that all of the jar files in a directory should be analyzed.
- auxClasspath
- An optional nested element which specifies a classpath (Jar files or directories) containing classes used by the analyzed library or application, but which you don’t want to analyze. It is specified the same way as Ant’s classpath element for the Java task.
- sourcePath
- An optional nested element which specifies a source directory path containing source files used to compile the Java code being analyzed. By specifying a source path, any generated XML bug output will have complete source information, which allows later viewing in the GUI.
- home
- A required attribute. It must be set to the name of the directory where SpotBugs is installed.
- quietErrors
- An optional boolean attribute. If true, reports of serious analysis errors and missing classes will be suppressed in the SpotBugs output. Default is false.
- reportLevel
- An optional attribute. It specifies the confidence/priority threshold for reporting issues.
If set to
low
, confidence is not used to filter bugs. If set tomedium
(the default), low confidence issues are supressed. If set tohigh
, only high confidence bugs are reported. - output
- Optional attribute. It specifies the output format. If set to
xml
(the default), output is in XML format. If set to “xml:withMessages”, output is in XML format augmented with human-readable messages. (You should use this format if you plan to generate a report using an XSL stylesheet.) If set to “html”, output is in HTML formatted (default stylesheet is default.xsl). If set totext
, output is in ad-hoc text format. If set toemacs
, output is in Emacs error message format. If set toxdocs
, output is xdoc XML for use with Apache Maven. - stylesheet
- Optional attribute. It specifies the stylesheet to use to generate html output when the output is set to html. Stylesheets included in the FindBugs distribution include default.xsl, fancy.xsl, fancy-hist.xsl, plain.xsl, and summary.xsl. The default value, if no stylesheet attribute is provided, is default.xsl.
- sort
- Optional attribute. If the output attribute is set to
text
, then the sort attribute specifies whether or not reported bugs are sorted by class. Default istrue
. - outputFile
- Optional attribute. If specified, names the output file in which the FindBugs output will be saved. By default, the output is displayed directly by Ant.
- debug
- Optional boolean attribute. If set to
true
, SpotBugs prints diagnostic information about which classes are being analyzed, and which bug pattern detectors are being run. Default isfalse
. - effort
- Set the analysis effort level. The value specified should be one of
min
,default
, ormax
. See Command-line Options <running.html#command-line-options>: for more information about setting the analysis level. - conserveSpace
- Synonym for
effort="min"
. - workHard
- Synonym for
effort="max"
. - visitors
- Optional attribute. It specifies a comma-separated list of bug detectors which should be run. The bug detectors are specified by their class names, without any package qualification. By default, all detectors which are not disabled by default are run.
- omitVisitors
- Optional attribute. It specifies a comma-separated list of bug detectors. It is like the visitors attribute, except it specifies detectors which will not be run.
- chooseVisitors
- Optional attribute. It specifies a comma-separated list of bug detectors prefixed with “+” or “-” to selectively enable/disable them.
- excludeFilter
- Optional attribute. It specifies the filename of a filter specifying bugs to exclude from being reported. See Filter file.
- includeFilter
- Optional attribute. It specifies the filename of a filter specifying which bugs are reported. See Filter file.
- projectFile
- Optional attribute. It specifies the name of a project file.
Project files are created by the FindBugs GUI, and specify classes, aux classpath entries, and source directories.
By naming a project, you don’t need to specify any class elements, nor do you need to specify
auxClasspath
orsourcePath
attributes. See Running SpotBugs for how to create a project. - jvmargs
- Optional attribute. It specifies any arguments that should be passed to the Java virtual machine used to run SpotBugs. You may need to use this attribute to specify flags to increase the amount of memory the JVM may use if you are analyzing a very large program.
- systemProperty
- Optional nested element. If specified, defines a system property. The name attribute specifies the name of the system property, and the value attribute specifies the value of the system property.
- timeout
- Optional attribute. It specifies the amount of time, in milliseconds, that the Java process executing SpotBugs may run before it is assumed to be hung and is terminated. The default is 600,000 milliseconds, which is ten minutes. Note that for very large programs, SpotBugs may require more than ten minutes to complete its analysis.
- failOnError
- Optional boolean attribute. Whether to abort the build process if there is an error running SpotBugs. Defaults to
false
. - errorProperty
- Optional attribute which specifies the name of a property that will be set to
true
if an error occurs while running SpotBugs. - warningsProperty
- Optional attribute which specifies the name of a property that will be set to
true
if any warnings are reported by SpotBugs on the analyzed program. - userPreferencesFile
- Optional attribute. Set the path of the user preferences file to use, which might override some of the options above.
Specifying
userPreferencesFile
as first argument would mean some later options will override them, as last argument would mean they will override some previous options). This rationale behind this option is to reuse SpotBugs Eclipse project settings for command line execution. - nested
- Optional attribute which enables or disables scanning of nested jar and zip files found in the list of files and directories to be analyzed. By default, scanning of nested jar/zip files is enabled.
- setExitCode
- Optional boolean attribute. Whether the exit code will be returned to the main ant job. Defaults to
true
.
Filter file¶
Filter files may be used to include or exclude bug reports for particular classes and methods. This chapter explains how to use filter files.
Introduction to Filter Files¶
Conceptually, a filter matches bug instances against a set of criteria. By defining a filter, you can select bug instances for special treatment; for example, to exclude or include them in a report.
A filter file is an XML document with a top-level FindBugsFilter
element which has some number of Match elements as children.
Each Match element represents a predicate which is applied to generated bug instances.
Usually, a filter will be used to exclude bug instances. For example:
$ spotbugs -textui -exclude myExcludeFilter.xml myApp.jar
However, a filter could also be used to select bug instances to specifically report:
$ spotbugs -textui -include myIncludeFilter.xml myApp.jar
Match
elements contain children, which are conjuncts of the predicate.
In other words, each of the children must be true
for the predicate to be true
.
Types of Match clauses¶
<Bug>¶
This element specifies a particular bug pattern or patterns to match. The ``pattern
attribute is a comma-separated list of bug pattern types.
You can find the bug pattern types for particular warnings by looking at the output produced by the -xml output option (the type attribute of BugInstance elements), or from the 検知å¯èƒ½ãªãƒã‚°ã®è©³ç´°.
For more coarse-grained matching, use code
attribute. It takes a comma-separated list of bug abbreviations. For most-coarse grained matching use category
attriute, that takes a comma separated list of bug category names: CORRECTNESS
, MT_CORRECTNESS
, BAD_PRACTICICE
, PERFORMANCE
, STYLE
.
If more than one of the attributes mentioned above are specified on the same <Bug> element, all bug patterns that match either one of specified pattern names, or abreviations, or categories will be matched.
As a backwards compatibility measure, <BugPattern> and <BugCode> elements may be used instead of <Bug> element. Each of these uses a name attribute for specifying accepted values list. Support for these elements may be removed in a future release.
<Confidence>¶
This element matches warnings with a particular bug confidence. The value
attribute should be an integer value: 1 to match high-confidence warnings, 2 to match normal-confidence warnings, or 3 to match low-confidence warnings. <Confidence>
replaced <Priority>
in 2.0.0 release.
<Priority>¶
Same as <Confidence>
, exists for backward compatibility.
<Rank>¶
This element matches warnings with a particular bug rank. The value
attribute should be an integer value between 1 and 20, where 1 to 4 are scariest, 5 to 9 scary, 10 to 14 troubling, and 15 to 20 of concern bugs.
<Package>¶
This element matches warnings associated with classes within the package specified using name
attribute. Nested packages are not included (along the lines of Java import statement). However matching multiple packages can be achieved easily using regex name match.
<Class>¶
This element matches warnings associated with a particular class. The name
attribute is used to specify the exact or regex match pattern for the class name. The role
attribute is the class role.
As a backward compatibility measure, instead of element of this type, you can use class
attribute on a Match
element to specify exact an class name or classregex
attribute to specify a regular expression to match the class name against.
If the Match
element contains neither a Class
element, nor a class
/ classregex
attribute, the predicate will apply to all classes. Such predicate is likely to match more bug instances than you want, unless it is refined further down with appropriate method or field predicates.
<Source>¶
This element matches warnings associated with a particular source file. The name
attribute is used to specify the exact or regex match pattern for the source file name.
<Method>¶
This element specifies a method. The name
attribute is used to specify the exact or regex match pattern for the method name. The params
attribute is a comma-separated list of the types of the method’s parameters. The returns
attribute is the method’s return type. The role
attribute is the method role. In params
and returns
, class names must be fully qualified. (E.g., "java.lang.String"
instead of just "String"
.) If one of the latter attributes is specified the other is required for creating a method signature. Note that you can provide either name
attribute or params
and returns
attributes or all three of them. This way you can provide various kinds of name and signature based matches.
<Field>¶
This element specifies a field. The name
attribute is used to specify the exact or regex match pattern for the field name. You can also filter fields according to their signature - use type
attribute to specify fully qualified type of the field. You can specify either or both of these attributes in order to perform name / signature based matches. The role
attribute is the field role.
<Local>¶
This element specifies a local variable. The name
attribute is used to specify the exact or regex match pattern for the local variable name. Local variables are variables defined within a method.
<Type>¶
This element matches warnings associated with a particular type. The descriptor
attribute is used to specify the exact or regex match pattern for type descriptor. If the descriptor starts with the ~ character the rest of attribute content is interpreted as a Java regular expression. The role
attribute is the class role, and the typeParameters
is the type parameters. Both of role
and typeParameters
are optional attributes.
<Or>¶
This element combines Match
clauses as disjuncts. I.e., you can put two Method
elements in an Or
clause in order to match either method.
<And>¶
This element combines Match
clauses which both must evaluate to true
. I.e., you can put Bug
and Confidence
elements in an And
clause in order to match specific bugs with given confidence only.
<Not>¶
This element inverts the included child Match
. I.e., you can put a Bug
element in a Not
clause in order to match any bug excluding the given one.
Java element name matching¶
If the name
attribute of Class
, Source
, Method
or Field
starts with the ~
character the rest of attribute content is interpreted as a Java regular expression that is matched against the names of the Java element in question.
Note that the pattern is matched against whole element name and therefore .*
clauses need to be used at pattern beginning and/or end to perform substring matching.
See java.util.regex.Pattern documentation for pattern syntax.
Caveats¶
Match
clauses can only match information that is actually contained in the bug instances.
Every bug instance has a class, so in general, excluding bugs by class will work.
Some bug instances have two (or more) classes.
For example, the DE (dropped exception) bugs report both the class containing the method where the dropped exception happens, and the class which represents the type of the dropped exception.
Only the first (primary) class is matched against Match
clauses.
So, for example, if you want to suppress IC (initialization circularity) reports for classes “com.foobar.A” and “com.foobar.B”, you would use two Match
clauses:
<Match>
<Class name="com.foobar.A" />
<Bug code="IC" />
</Match>
<Match>
<Class name="com.foobar.B" />
<Bug code="IC" />
</Match>
By explicitly matching both classes, you ensure that the IC bug instance will be matched regardless of which class involved in the circularity happens to be listed first in the bug instance. (Of course, this approach might accidentally supress circularities involving “com.foobar.A” or “com.foobar.B” and a third class.)
Many kinds of bugs report what method they occur in. For those bug instances, you can put Method clauses in the Match element and they should work as expected.
Examples¶
Match all bug reports for a class¶
<Match>
<Class name="com.foobar.MyClass" />
</Match>
Match certain tests from a class by specifying their abbreviations¶
<Match>
<Class name="com.foobar.MyClass"/ >
<Bug code="DE,UrF,SIC" />
</Match>
Match certain tests from all classes by specifying their abbreviations¶
<Match>
<Bug code="DE,UrF,SIC" />
</Match>
Match certain tests from all classes by specifying their category¶
<Match>
<Bug category="PERFORMANCE" />
</Match>
Match bug types from specified methods of a class by their abbreviations¶
<Match>
<Class name="com.foobar.MyClass" />
<Or>
<Method name="frob" params="int,java.lang.String" returns="void" />
<Method name="blat" params="" returns="boolean" />
</Or>
<Bug code="DC" />
</Match>
Match a particular bug pattern in a particular method¶
<!-- A method with an open stream false positive. -->
<Match>
<Class name="com.foobar.MyClass" />
<Method name="writeDataToFile" />
<Bug pattern="OS_OPEN_STREAM" />
</Match>
Match a particular bug pattern with a given priority in a particular method¶
<!-- A method with a dead local store false positive (medium priority). -->
<Match>
<Class name="com.foobar.MyClass" />
<Method name="someMethod" />
<Bug pattern="DLS_DEAD_LOCAL_STORE" />
<Priority value="2" />
</Match>
Match minor bugs introduced by AspectJ compiler (you are probably not interested in these unless you are an AspectJ developer)¶
<Match>
<Class name="~.*\$AjcClosure\d+" />
<Bug pattern="DLS_DEAD_LOCAL_STORE" />
<Method name="run" />
</Match>
<Match>
<Bug pattern="UUF_UNUSED_FIELD" />
<Field name="~ajc\$.*" />
</Match>
Match bugs in specific parts of the code base¶
<!-- match unused fields warnings in Messages classes in all packages -->
<Match>
<Class name="~.*\.Messages" />
<Bug code="UUF" />
</Match>
<!-- match mutable statics warnings in all internal packages -->
<Match>
<Package name="~.*\.internal" />
<Bug code="MS" />
</Match>
<!-- match anonymoous inner classes warnings in ui package hierarchy -->
<Match>
<Package name="~com\.foobar\.fooproject\.ui.*" />
<Bug pattern="SIC_INNER_SHOULD_BE_STATIC_ANON" />
</Match>
Match bugs on fields or methods with specific signatures¶
<!-- match System.exit(...) usage warnings in void main(String[]) methods in all classes -->
<Match>
<Method returns="void" name="main" params="java.lang.String[]" />
<Bug pattern="DM_EXIT" />
</Match>
<!-- match UuF warnings on fields of type com.foobar.DebugInfo on all classes -->
<Match>
<Field type="com.foobar.DebugInfo" />
<Bug code="UuF" />
</Match>
Match bugs using the Not filter operator¶
<!-- ignore all bugs in test classes, except for those bugs specifically relating to JUnit tests -->
<!-- i.e. filter bug if ( classIsJUnitTest && ! bugIsRelatedToJUnit ) -->
<Match>
<!-- the Match filter is equivalent to a logical 'And' -->
<Class name="~.*\.*Test" />
<!-- test classes are suffixed by 'Test' -->
<Not>
<Bug code="IJU" /> <!-- 'IJU' is the code for bugs related to JUnit test code -->
</Not>
</Match>
Full exclusion filter file to match all classes generated from Groovy source files¶
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<Source name="~.*\.groovy" />
</Match>
</FindBugsFilter>
Complete Example¶
<FindBugsFilter>
<Match>
<Class name="com.foobar.ClassNotToBeAnalyzed" />
</Match>
<Match>
<Class name="com.foobar.ClassWithSomeBugsMatched" />
<Bug code="DE,UrF,SIC" />
</Match>
<!-- Match all XYZ violations. -->
<Match>
<Bug code="XYZ" />
</Match>
<!-- Match all doublecheck violations in these methods of "AnotherClass". -->
<Match>
<Class name="com.foobar.AnotherClass" />
<Or>
<Method name="nonOverloadedMethod" />
<Method name="frob" params="int,java.lang.String" returns="void" />
<Method name="blat" params="" returns="boolean" />
</Or>
<Bug code="DC" />
</Match>
<!-- A method with a dead local store false positive (medium priority). -->
<Match>
<Class name="com.foobar.MyClass" />
<Method name="someMethod" />
<Bug pattern="DLS_DEAD_LOCAL_STORE" />
<Priority value="2" />
</Match>
<!-- All bugs in test classes, except for JUnit-specific bugs -->
<Match>
<Class name="~.*\.*Test" />
<Not>
<Bug code="IJU" />
</Not>
</Match>
</FindBugsFilter>
Analysis Properties¶
SpotBugs allows several aspects of the analyses it performs to be customized. System properties are used to configure these options. This chapter describes the configurable analysis options.
The analysis options have two main purposes. First, they allow you to inform SpotBugs about the meaning of methods in your application, so that it can produce more accurate results, or produce fewer false warnings. Second, they allow you to configure the precision of the analysis performed. Reducing analysis precision can save memory and analysis time, at the expense of missing some real bugs, or producing more false warnings.
The analysis options are set using the -property
command line option. For example:
$ spotbugs -textui -property "cfg.noprune=true" myApp.jar
The list of configurable analysis properties is shown in following table:
Property Name | Value | Meaning |
---|---|---|
findbugs.assertionmethods | Comma-separated list of fully qualified method names: e.g., “com.foo.MyClass.checkAssertion” | This property specifies the names of methods that are used to check program assertions. Specifying these methods allows the null pointer dereference bug detector to avoid reporting false warnings for values which are checked by assertion methods. |
findbugs.de.comment | true or false | If true, the DroppedException detector scans source code for empty catch blocks for a comment, and if one is found, does not report a warning. |
findbugs.maskedfields.locals | true or false | If true, emit low priority warnings for local variables which obscure fields. Default is false. |
findbugs.nullderef.assumensp | true or false | not used (intention: If true, the null dereference detector assumes that any reference value returned from a method or passed to a method in a parameter might be null. Default is false. Note that enabling this property will very likely cause a large number of false warnings to be produced.) |
findbugs.refcomp.reportAll | true or false | If true, all suspicious reference comparisons using the == and != operators are reported.,If false, only one such warning is issued per method.,Default is false. |
findbugs.sf.comment | true or false | If true, the SwitchFallthrough detector will only report warnings for cases where the source code does not have a comment containing the words “fall” or “nobreak”. (An accurate source path must be used for this feature to work correctly.) This helps find cases where the switch fallthrough is likely to be unintentional. |
Implement SpotBugs plugin¶
Create Maven project¶
Use spotbugs-archetype to create Maven project. Then Maven archetype plugin will ask you to decide plugin’s groupId, artifactId, package and initial version.
$ mvn archetype:generate \
-DarchetypeArtifactId=spotbugs-archetype \
-DarchetypeGroupId=com.github.spotbugs \
-DarchetypeVersion=0.1.0
Write java code to represent bug to find¶
In generated project, you can find a file named as BadCase.java. Update this file to represent the target bug to find.
If you have multiple patterns to represent, add more classes into src/test/java
directory.
Write test case to ensure your detector can find bug¶
In generated project, you can find another file named as MyDetectorTest.java.
The spotbugs.performAnalysis(Path)
in this test runs SpotBugs with your plugin, and return all found bugs (here 1st argument of this method is a path of class file compiled from BadCase.java
).
You can use BugInstanceMatcher to verify that your plugin can find bug as expected.
Currently this test should fail, because we’ve not updated detector itself yet.
Write java code to avoid false-positive¶
To avoid false-positive, it is good to ensure that in which case detector should NOT find bug.
Update GoodCase.java in your project, and represent such cases.
After that, add a test method into MyDetectorTest.java
which verify that no bug found from this GoodCase
class.
If you have multiple patterns to represent, add more classes into src/test/java
directory.
Update detector to pass all unit tests¶
Now you have tests to ensure that your detector can work as expected.
注釈
TBU
Which super class you should choose¶
- AnnotationDetector
- Base detector which analyzes annotations on classes, fields, methods, and method parameters.
- BytecodeScanningDetector
- Base detector which analyzes java bytecode in class files.
- OpcodeStackDetector
- Sub class of
BytecodeScanningDetector
, which can scan the bytecode of a method and use an operand stack.
Update findbugs.xml¶
SpotBugs reads findbugs.xml
in each plugin to find detectors and bugs.
So when you add new detector, you need to add new <Detector>
element like below:
<Detector class="com.github.plugin.MyDetector" reports="MY_BUG" speed="fast" />
It is also necessary to add <BugPattern>
, to describe type and category of your bug pattern.
<BugPattern type="MY_BUG" category="CORRECTNESS" />
You can find findbugs.xml
in src/main/resources
directory of generated Maven project.
Update messages.xml¶
SpotBugs reads messages.xml
in each plugin to construct human readable message to report detected bug.
It also supports reading localized messages from messages_ja.xml
, messages_fr.xml
and so on.
You can find messages.xml
in src/main/resources
directory of generated Maven project.
Update message of Detector¶
In <Detector>
element, you can add detector’s description message. Note that it should be plain text, HTML is not supported.
<Detector class="com.github.plugin.MyDetector">
<Details>
Original detector to detect MY_BUG bug pattern.
</Details>
</Detector>
Update message of Bug Pattern¶
In <BugPattern>
element, you can add bug pattern’s description message.
There are three kinds of messages:
- ShortDescription
- Short description for bug pattern. Useful to tell its intent and character for users. It should be plain text, HTML is not supported.
- LongDescription
Longer description for bug pattern. You can use placeholder like
{0}
(0-indexed), then added data into BugInstance will be inserted at there. So thisLongDescription
is useful to tell detailed information about detected bug.It should be plain text, HTML is not supported.
- Details
- Detailed description for bug pattern. It should be HTML format, so this is useful to tell detailed specs/examples with table, list and code snippets.
<BugPattern type="MY_BUG">
<ShortDescription>Explain bug pattern shortly.</ShortDescription>
<LongDescription>
Explain existing problem in code, and how developer should improve their implementation.
</LongDescription>
<Details>
<![CDATA[
<p>Explain existing problem in code, and how developer should improve their implementation.</p>
]]>
</Details>
</BugPattern>
SpotBugs FAQ¶
This document contains answers to frequently asked questions about SpotBugs. If you just want general information about SpotBugs, have a look at the manual.
Q1: I’m getting java.lang.UnsupportedClassVersionError when I try to run SpotBugs¶
SpotBugs requires JRE8 or later to run. If you use an earlier version, you will see an exception error message similar to the following:
Exception in thread “main” java.lang.UnsupportedClassVersionError: edu/umd/cs/findbugs/gui/FindBugsFrame (Unsupported major.minor version 52.0)
The solution is to upgrade to JRE8 or later.
Q2: SpotBugs is running out of memory, or is taking a long time to finish¶
In general, SpotBugs requires lots of memory and a relatively fast CPU. For large applications, 1024M or more of heap space may be required.
By default, SpotBugs allocates 768M of heap space.
You can increase this using the -maxHeap n
option, where n is the number of megabytes of heap space to allocate.
Q3: What is the “auxiliary classpath”? Why should I specify it?¶
Many important facts about a Java class require information about the classes that it references. For example:
- What other classes and interfaces the class inherits from
- What exceptions can be thrown by methods in external classes and interfaces
The “auxiliary classpath” is a list of Jar files, directories, and class files containing classes that are used by the code you want SpotBugs to analyze, but should not themselves be analyzed by SpotBugs.
If SpotBugs doesn’t have complete information about referenced classes, it will not be able to produce results that are as accurate as possible. For example, having a complete repository of referenced classes allows SpotBugs to prune control flow information so it can concentrate on paths through methods that are most likely to be feasible at runtime. Also, some bug detectors (such as the suspicious reference comparison detector) rely on being able to perform type inference, which requires complete type hierarchy information.
For these reasons, we strongly recommend that you completely specify the auxiliary classpath when you run SpotBugs.
You can do this by using the -auxclasspath
command line option, or the “Classpath entries” list in the GUI project editor dialog.
If SpotBugs cannot find a class referenced by your application, it will print out a message when the analysis completes, specifying the classes that were missing. You should modify the auxiliary classpath to specify how to find the missing classes, and then run SpotBugs again.
Q4: The Eclipse plugin doesn’t load¶
The symptom of this problem is that Eclipse fails to load the SpotBugs UI plugin with the message:
Plug-in “edu.umd.cs.findbugs.plugin.eclipse” was disabled due to missing or disabled prerequisite plug-in “org.eclipse.ui.ide”
The reason for this problem is that the Eclipse plugin distributed with SpotBugs does not work with older 3.x versions of Eclipse. Please use Eclipse Neon (version 4.6) or newer.
Q5: I’m getting a lot of false “OS” and “ODR” warnings¶
By default, SpotBugs assumes that any method invocation can throw an unchecked runtime exception.
As a result, it may assume that an unchecked exception thrown out of the method could bypass a call to a close()
method for a stream or database resource.
You can use the -workHard
command line argument or the findbugs.workHard
boolean analysis property to make SpotBugs work harder to prune unlikely exception edges.
This generally reduces the number of false warnings, at the expense of slowing down the analysis.
Q6: The Eclipse plugin loads, but doesn’t work correctly¶
- Make sure the Java code you trying to analyze is built properly and has no classpath or compile errors.
- Make sure the project and workspace SpotBugs settings are valid - in doubt, revert them to defaults.
- Make sure the Error log view does not show errors.
SpotBugs Links¶
This page contains links to related projects, including tools that are similar to SpotBugs.
SpotBugs Plugins¶
- fb-contrib
- A FindBugs/SpotBugs plugin for doing static code analysis on java byte code.
- Find Security Bugs
- A FindBugs/SpotBugs plugin for security audits of Java web applications.
- findbugs-slf4j
- A FindBugs/SpotBugs plugin to verify usage of SLF4J.
検知å¯èƒ½ãªãƒã‚°ã®è©³ç´°Â¶
ã“ã®ãƒšãƒ¼ã‚¸ã§ã¯SpotBugsãŒæ¨™æº–ã§æ¤œçŸ¥å¯èƒ½ãªãƒã‚°ã‚’一覧ã§ç´¹ä»‹ã—ã¦ã„ã¾ã™ã€‚
ãƒãƒƒãƒ‰ãƒ—ラクティス (BAD_PRACTICE)¶
Violations of recommended and essential coding practice. Examples include hash code and equals problems, cloneable idiom, dropped exceptions, Serializable problems, and misuse of finalize. We strive to make this analysis accurate, although some groups may not care about some of the bad practices.
CNT: 既知ã®å®šæ•°ã®é›‘ãªå€¤ã‚’見ã¤ã‘㟠(CNT_ROUGH_CONSTANT_VALUE)¶
It's recommended to use the predefined library constant for code clarity and better precision.
NP: 戻り型㌠Boolean ã®ãƒ¡ã‚½ãƒƒãƒ‰ãŒæ˜Žç¤ºçš„ã« null ã‚’è¿”ã—ã¦ã„ã‚‹ (NP_BOOLEAN_RETURN_NULL)¶
A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException.
SW: Swing メソッド㯠AWT イベントディスパッãƒã‚¹ãƒ¬ãƒƒãƒ‰ã‹ã‚‰å‘¼ã³å‡ºã™å¿…è¦ãŒã‚ã‚‹ (SW_SWING_METHODS_INVOKED_IN_SWING_THREAD)¶
(From JDC Tech Tip): The Swing methods show(), setVisible(), and pack() will create the associated peer for the frame. With the creation of the peer, the system creates the event dispatch thread. This makes things problematic because the event dispatch thread could be notifying listeners while pack and validate are still processing. This situation could result in two threads going through the Swing component-based GUI -- it's a serious flaw that could result in deadlocks or other related threading issues. A pack call causes components to be realized. As they are being realized (that is, not necessarily visible), they could trigger listener notification on the event dispatch thread.
FI: ファイナライザã¯ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’ null ã«ã™ã‚‹ã ã‘ (FI_FINALIZER_ONLY_NULLS_FIELDS)¶
This finalizer does nothing except null out fields. This is completely pointless, and requires that the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize method.
FI: ファイナライザã¯ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’ null ã«ã™ã‚‹ (FI_FINALIZER_NULLS_FIELDS)¶
This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, and the object is going to be garbage collected anyway.
UI: クラスãŒæ‹¡å¼µã•ã‚Œã‚‹ãªã‚‰ getResource ã®ä½¿ã„æ–¹ã¯å®‰å…¨ã§ã¯ãªã„ã‹ã‚‚ã—ã‚Œãªã„ (UI_INHERITANCE_UNSAFE_GETRESOURCE)¶
Calling this.getClass().getResource(...)
could give
results other than expected if this class is extended by a class in
another package.
AM: 空㮠ZIP ファイルエントリã®ä½œæˆ (AM_CREATES_EMPTY_ZIP_FILE_ENTRY)¶
The code calls putNextEntry()
, immediately
followed by a call to closeEntry()
. This results
in an empty ZipFile entry. The contents of the entry
should be written to the ZipFile between the calls to
putNextEntry()
and
closeEntry()
.
AM: 空㮠JAR ファイルエントリã®ä½œæˆ (AM_CREATES_EMPTY_JAR_FILE_ENTRY)¶
The code calls putNextEntry()
, immediately
followed by a call to closeEntry()
. This results
in an empty JarFile entry. The contents of the entry
should be written to the JarFile between the calls to
putNextEntry()
and
closeEntry()
.
IMSE: ç–‘ã‚ã—ã„ IllegalMonitorStateException ã®ã‚ャッム(IMSE_DONT_CATCH_IMSE)¶
IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on).
CN: Cloneable を実装ã—ã¦ã„ãªã„クラス㌠clone メソッドを定義ã—ã¦ã„ã‚‹ (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)¶
This class defines a clone() method but the class doesn't implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended.
CN: Cloneable を実装ã—ãŸã‚¯ãƒ©ã‚¹ãŒ clone メソッドを定義も使用もã—ã¦ã„ãªã„ (CN_IDIOM)¶
Class implements Cloneable but does not define or use the clone method.
CN: clone メソッド㌠super.clone() を呼ã³å‡ºã—ã¦ã„ãªã„ (CN_IDIOM_NO_SUPER_CALL)¶
This non-final class defines a clone() method that does not call super.clone(). If this class ("A") is extended by a subclass ("B"), and the subclass B calls super.clone(), then it is likely that B's clone() method will return an object of type A, which violates the standard contract for clone().
If all clone() methods call super.clone(), then they are guaranteed to use Object.clone(), which always returns an object of the correct type.
DE: 例外をæ¨ã¦ã¦ã„ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (DE_MIGHT_DROP)¶
This method might drop an exception. In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.
DE: 例外を無視ã—ã¦ã„ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (DE_MIGHT_IGNORE)¶
This method might ignore an exception. In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.
Dm: System.exit(...) を呼ã³å‡ºã—ã¦ã„るメソッド (DM_EXIT)¶
Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.
Nm: Java ã®å¾Œã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã®ã‚ーワードã§ã‚ã‚‹è˜åˆ¥åを使用ã—ã¦ã„ã‚‹ (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)¶
The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed in order to compile it in later versions of Java.
Nm: Java ã®å¾Œã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã®ã‚ーワードã§ã‚ã‚‹è˜åˆ¥åを使用ã—ã¦ã„ã‚‹ (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)¶
This identifier is used as a keyword in later versions of Java. This code, and any code that references this API, will need to be changed in order to compile it in later versions of Java.
JCIP: ä¸å¤‰ã‚¯ãƒ©ã‚¹ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã¯ final ã«ã™ã¹ã (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)¶
The class is annotated with net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable, and the rules for those annotations require that all fields are final. .
Dm: å±é™ºãªãƒ¡ã‚½ãƒƒãƒ‰ runFinalizersOnExit を呼ã³å‡ºã—ã¦ã„るメソッド (DM_RUN_FINALIZERS_ON_EXIT)¶
Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: they are among the most dangerous methods in the Java libraries. -- Joshua Bloch
NP: equals メソッド㯠null ã®å¼•æ•°ã‚’ãƒã‚§ãƒƒã‚¯ã—ã¦ã„ãªã„ (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)¶
This implementation of equals(Object) violates the contract defined by java.lang.Object.equals() because it does not check for null being passed as the argument. All equals() methods should return false if passed a null value.
FI: 空ã®ãƒ•ã‚¡ã‚¤ãƒŠãƒ©ã‚¤ã‚¶ã¯å‰Šé™¤ã™ã¹ã (FI_EMPTY)¶
Empty finalize()
methods are useless, so they should
be deleted.
FI: ファイナライザã¯ã‚¹ãƒ¼ãƒ‘ークラスã®ãƒ•ã‚¡ã‚¤ãƒŠãƒ©ã‚¤ã‚¶ã‚’無効ã«ã—ã¦ã„ã‚‹ (FI_NULLIFY_SUPER)¶
This empty finalize()
method explicitly negates the
effect of any finalizer defined by its superclass. Any finalizer
actions defined for the superclass will not be performed.
Unless this is intended, delete this method.
FI: ファイナライザã¯ã‚¹ãƒ¼ãƒ‘ークラスã®ãƒ•ã‚¡ã‚¤ãƒŠãƒ©ã‚¤ã‚¶ã‚’呼ã³å‡ºã—ã¦ã„ã‚‹ã ã‘ (FI_USELESS)¶
The only thing this finalize()
method does is call
the superclass's finalize()
method, making it
redundant. Delete it.
FI: ファイナライザã¯ã‚¹ãƒ¼ãƒ‘ークラスã®ãƒ•ã‚¡ã‚¤ãƒŠãƒ©ã‚¤ã‚¶ã‚’呼ã³å‡ºã—ã¦ã„ãªã„ (FI_MISSING_SUPER_CALL)¶
This finalize()
method does not make a call to its
superclass's finalize()
method. So, any finalizer
actions defined for the superclass will not be performed.
Add a call to super.finalize()
.
FI: ファイナライザã®æ˜Žç¤ºçš„ãªå‘¼ã³å‡ºã— (FI_EXPLICIT_INVOCATION)¶
This method contains an explicit invocation of the finalize()
method on an object. Because finalizer methods are supposed to be
executed once, and only by the VM, this is a bad idea.
If a connected set of objects beings finalizable, then the VM will invoke the finalize method on all the finalizable object, possibly at the same time in different threads. Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize on objects referenced by X, because they may already be getting finalized in a separate thread.
Eq: equals メソッドã¯äº’æ›æ€§ã®ãªã„オペランドをãƒã‚§ãƒƒã‚¯ã—ã¦ã„ã‚‹ (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)¶
This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like:
public boolean equals(Object o) {
if (o instanceof Foo)
return name.equals(((Foo)o).name);
else if (o instanceof String)
return name.equals(o);
else return false;
}
This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behaviors are possible.
Eq: equals メソッドã¯ã‚µãƒ–タイプã®ãŸã‚ã«å¤±æ•—ã™ã‚‹ (EQ_GETCLASS_AND_CLASS_CONSTANT)¶
This class has an equals method that will be broken if it is inherited by subclasses.
It compares a class literal with the class of the argument (e.g., in class Foo
it might check if Foo.class == o.getClass()
).
It is better to check if this.getClass() == o.getClass()
.
Eq: 共変㪠equals メソッドã®å®šç¾© (EQ_SELF_NO_OBJECT)¶
This class defines a covariant version of equals()
.
To correctly override the equals()
method in
java.lang.Object
, the parameter of equals()
must have type java.lang.Object
.
Co: 共変㪠compareTo メソッドã®å®šç¾© (CO_SELF_NO_OBJECT)¶
This class defines a covariant version of compareTo()
.
To correctly override the compareTo()
method in the
Comparable
interface, the parameter of compareTo()
must have type java.lang.Object
.
Co: compareTo()/compare() 㯠Integer.MIN_VALUE を返㙠(CO_COMPARETO_RESULTS_MIN_VALUE)¶
In some situation, this compareTo or compare method returns the constant Integer.MIN_VALUE, which is an exceptionally bad practice. The only thing that matters about the return value of compareTo is the sign of the result. But people will sometimes negate the return value of compareTo, expecting that this will negate the sign of the result. And it will, except in the case where the value returned is Integer.MIN_VALUE. So just return -1 rather than Integer.MIN_VALUE.
Co: compareTo()/compare() ã¯é–“é•ã£ã¦ float ã¾ãŸã¯ double 値を処ç†ã™ã‚‹ (CO_COMPARETO_INCORRECT_FLOATING)¶
This method compares double or float values using pattern like this: val1 > val2 ? 1 : val1 < val2 ? -1 : 0. This pattern works incorrectly for -0.0 and NaN values which may result in incorrect sorting result or broken collection (if compared values are used as keys). Consider using Double.compare or Float.compare static methods which handle all the special cases correctly.
RV: compareTo()/compare() ã®çµæžœã‚’無効ã«ã™ã‚‹ (RV_NEGATING_RESULT_OF_COMPARETO)¶
This code negatives the return value of a compareTo or compare method. This is a questionable or bad programming practice, since if the return value is Integer.MIN_VALUE, negating the return value won't negate the sign of the result. You can achieve the same intended result by reversing the order of the operands rather than by negating the results.
ES: String オブジェクトを == ã‚„ != を使用ã—ã¦æ¯”較ã—ã¦ã„ã‚‹ (ES_COMPARING_STRINGS_WITH_EQ)¶
This code compares java.lang.String
objects for reference
equality using the == or != operators.
Unless both strings are either constants in a source file, or have been
interned using the String.intern()
method, the same string
value may be represented by two different String objects. Consider
using the equals(Object)
method instead.
ES: String パラメータを == ã‚„ != を使用ã—ã¦æ¯”較ã—ã¦ã„ã‚‹ (ES_COMPARING_PARAMETER_STRING_WITH_EQ)¶
This code compares a java.lang.String
parameter for reference
equality using the == or != operators. Requiring callers to
pass only String constants or interned strings to a method is unnecessarily
fragile, and rarely leads to measurable performance gains. Consider
using the equals(Object)
method instead.
Eq: compareTo(...) メソッドを定義ã—㦠Object.equals() を使用ã—ã¦ã„るクラス (EQ_COMPARETO_USE_OBJECT_EQUALS)¶
This class defines a compareTo(...)
method but inherits its
equals()
method from java.lang.Object
.
Generally, the value of compareTo should return zero if and only if
equals returns true. If this is violated, weird and unpredictable
failures will occur in classes such as PriorityQueue.
In Java 5 the PriorityQueue.remove method uses the compareTo method,
while in Java 6 it uses the equals method.
From the JavaDoc for the compareTo method in the Comparable interface:
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))
.
Generally speaking, any class that implements the Comparable interface and violates this condition
should clearly indicate this fact. The recommended language
is "Note: this class has a natural ordering that is inconsistent with equals."
HE: hashCode メソッドを定義ã—㦠Object.equals() を使用ã—ã¦ã„るクラス (HE_HASHCODE_USE_OBJECT_EQUALS)¶
This class defines a hashCode()
method but inherits its
equals()
method from java.lang.Object
(which defines equality by comparing object references). Although
this will probably satisfy the contract that equal objects must have
equal hashcodes, it is probably not what was intended by overriding
the hashCode()
method. (Overriding hashCode()
implies that the object's identity is based on criteria more complicated
than simple reference equality.)
If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
the recommended hashCode
implementation to use is:
public int hashCode() {
assert false : "hashCode not designed";
return 42; // any arbitrary constant will do
}
HE: hashCode メソッドを定義ã—ã¦ã„ã¾ã™ãŒ equals メソッドã¯å®šç¾©ã—ã¦ã„ãªã„クラス (HE_HASHCODE_NO_EQUALS)¶
This class defines a hashCode()
method but not an
equals()
method. Therefore, the class may
violate the invariant that equal objects must have equal hashcodes.
HE: equals メソッドを定義ã—㦠Object.hashCode() を使用ã—ã¦ã„るクラス (HE_EQUALS_USE_HASHCODE)¶
This class overrides equals(Object)
, but does not
override hashCode()
, and inherits the implementation of
hashCode()
from java.lang.Object
(which returns
the identity hash code, an arbitrary value assigned to the object
by the VM). Therefore, the class is very likely to violate the
invariant that equal objects must have equal hashcodes.
If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
the recommended hashCode
implementation to use is:
public int hashCode() {
assert false : "hashCode not designed";
return 42; // any arbitrary constant will do
}
HE: equals メソッドを継承ã—㦠Object.hashCode() を使用ã—ã¦ã„るクラス (HE_INHERITS_EQUALS_USE_HASHCODE)¶
This class inherits equals(Object)
from an abstract
superclass, and hashCode()
from
java.lang.Object
(which returns
the identity hash code, an arbitrary value assigned to the object
by the VM). Therefore, the class is very likely to violate the
invariant that equal objects must have equal hashcodes.
If you don't want to define a hashCode method, and/or don't
believe the object will ever be put into a HashMap/Hashtable,
define the hashCode()
method
to throw UnsupportedOperationException
.
HE: equals メソッドã¯å®šç¾©ã—ã¦ã„ã¾ã™ãŒ hashCode メソッドã¯å®šç¾©ã—ã¦ã„ãªã„クラス (HE_EQUALS_NO_HASHCODE)¶
This class overrides equals(Object)
, but does not
override hashCode()
. Therefore, the class may violate the
invariant that equal objects must have equal hashcodes.
Eq: 抽象クラスã¯å…±å¤‰ãª equals メソッドを宣言ã—ã¦ã„ã‚‹ (EQ_ABSTRACT_SELF)¶
This class defines a covariant version of equals()
.
To correctly override the equals()
method in
java.lang.Object
, the parameter of equals()
must have type java.lang.Object
.
Co: 抽象クラスã¯å…±å¤‰ãª compareTo メソッドを定義ã—ã¦ã„ã‚‹ (CO_ABSTRACT_SELF)¶
This class defines a covariant version of compareTo()
.
To correctly override the compareTo()
method in the
Comparable
interface, the parameter of compareTo()
must have type java.lang.Object
.
IC: スーパークラスã¯åˆæœŸåŒ–ä¸ã«ã‚µãƒ–クラスを使用ã—ã¦ã„ã‚‹ (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)¶
During the initialization of a class, the class makes an active use of a subclass.
That subclass will not yet be initialized at the time of this use.
For example, in the following code, foo
will be null.
public class CircularClassInitialization {
static class InnerClassSingleton extends CircularClassInitialization {
static InnerClassSingleton singleton = new InnerClassSingleton();
}
static CircularClassInitialization foo = InnerClassSingleton.singleton;
}
SI: スタティックイニシャライザã¯ï¼Œã™ã¹ã¦ã® static final フィールドãŒä»£å…¥ã•ã‚Œã‚‹å‰ã«ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’作æˆã™ã‚‹ (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)¶
The class's static initializer creates an instance of the class before all of the static final fields are assigned.
It: Iterator.next() ㌠NoSuchElementException をスãƒãƒ¼ã§ããªã„ (IT_NO_SUCH_ELEMENT)¶
This class implements the java.util.Iterator
interface.
However, its next()
method is not capable of throwing
java.util.NoSuchElementException
. The next()
method should be changed so it throws NoSuchElementException
if is called when there are no more elements to return.
ME: 列挙型フィールド㯠public ã§å¯å¤‰ã§ã‚ã‚‹ (ME_MUTABLE_ENUM_FIELD)¶
A mutable public field is defined inside a public enum, thus can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world. Consider declaring this field final and/or package-private.
ME: public 列挙型メソッドãŒç„¡æ¡ä»¶ã«ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’è¨å®šã™ã‚‹ (ME_ENUM_FIELD_SETTER)¶
This public method declared in public enum unconditionally sets enum field, thus this field can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world. Consider removing this method or declaring it package-private.
Nm: メソッドåã¯å°æ–‡å—ã‹ã‚‰å§‹ã‚ã‚‹ã¹ã (NM_METHOD_NAMING_CONVENTION)¶
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
Nm: フィールドåã¯å°æ–‡å—ã‹ã‚‰å§‹ã‚ã‚‹ã¹ã (NM_FIELD_NAMING_CONVENTION)¶
Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized.
Nm: クラスåã¯å®Ÿè£…ã•ã‚ŒãŸã‚¤ãƒ³ã‚¿ãƒ•ã‚§ãƒ¼ã‚¹ã®å˜ç´”åã‚’é®ã‚‹ã¹ãã§ã¯ãªã„ (NM_SAME_SIMPLE_NAME_AS_INTERFACE)¶
This class/interface has a simple name that is identical to that of an implemented/extended interface, except
that the interface is in a different package (e.g., alpha.Foo
extends beta.Foo
).
This can be exceptionally confusing, create lots of situations in which you have to look at import statements
to resolve references and creates many
opportunities to accidentally define methods that do not override methods in their superclasses.
Nm: クラスåã¯ã‚¹ãƒ¼ãƒ‘ークラスã®å˜ç´”åã‚’é®ã‚‹ã¹ãã§ã¯ãªã„ (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)¶
This class has a simple name that is identical to that of its superclass, except
that its superclass is in a different package (e.g., alpha.Foo
extends beta.Foo
).
This can be exceptionally confusing, create lots of situations in which you have to look at import statements
to resolve references and creates many
opportunities to accidentally define methods that do not override methods in their superclasses.
Nm: クラスåã¯å¤§æ–‡å—ã‹ã‚‰å§‹ã‚ã‚‹ã¹ã (NM_CLASS_NAMING_CONVENTION)¶
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
Nm: éžå¸¸ã«ç´›ã‚‰ã‚ã—ã„åå‰ã®ãƒ¡ã‚½ãƒƒãƒ‰ (多分æ„図的) (NM_VERY_CONFUSING_INTENTIONAL)¶
The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other. From the existence of other methods, it seems that the existence of both of these methods is intentional, but is sure is confusing. You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs.
Nm: パラメータã®é–“é•ã£ãŸãƒ‘ッケージã®ãŸã‚ã«ã‚¹ãƒ¼ãƒ‘ークラスã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’オーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ãªã„メソッド (NM_WRONG_PACKAGE_INTENTIONAL)¶
The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:
import alpha.Foo;
public class A {
public int f(Foo x) { return 17; }
}
----
import beta.Foo;
public class B extends A {
public int f(Foo x) { return 42; }
public int f(alpha.Foo x) { return 27; }
}
The f(Foo)
method defined in class B
doesn't
override the
f(Foo)
method defined in class A
, because the argument
types are Foo
's from different packages.
In this case, the subclass does define a method with a signature identical to the method in the superclass, so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider removing or deprecating the method with the similar but not identical signature.
Nm: 紛らã‚ã—ã„åå‰ã®ãƒ¡ã‚½ãƒƒãƒ‰ (NM_CONFUSING)¶
The referenced methods have names that differ only by capitalization.
Nm: 例外クラスã®ã‚ˆã†ã«å‘½åã•ã‚Œã¦ã„ã‚‹ãŒï¼Œã‚¯ãƒ©ã‚¹ã¯ Exception ã‹ã‚‰æ´¾ç”Ÿã•ã‚Œã¦ã„ãªã„ (NM_CLASS_NOT_EXCEPTION)¶
This class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class.
RR: InputStream.read() ã®æˆ»ã‚Šå€¤ã‚’無視ã—ã¦ã„るメソッド (RR_NOT_CHECKED)¶
This method ignores the return value of one of the variants of
java.io.InputStream.read()
which can return multiple bytes.
If the return value is not checked, the caller will not be able to correctly
handle the case where fewer bytes were read than the caller requested.
This is a particularly insidious kind of bug, because in many programs,
reads from input streams usually do read the full amount of data requested,
causing the program to fail only sporadically.
RR: InputStream.skip() ã®æˆ»ã‚Šå€¤ã‚’無視ã—ã¦ã„るメソッド (SR_NOT_CHECKED)¶
This method ignores the return value of
java.io.InputStream.skip()
which can skip multiple bytes.
If the return value is not checked, the caller will not be able to correctly
handle the case where fewer bytes were skipped than the caller requested.
This is a particularly insidious kind of bug, because in many programs,
skips from input streams usually do skip the full amount of data requested,
causing the program to fail only sporadically. With Buffered streams, however,
skip() will only skip data in the buffer, and will routinely fail to skip the
requested number of bytes.
Se: Serializable ãªã‚¯ãƒ©ã‚¹ã®ã‚¹ãƒ¼ãƒ‘ークラスã§ï¼Œå¼•æ•°ãªã—コンストラクタを定義ã—ã¦ã„ãªã„ (SE_NO_SUITABLE_CONSTRUCTOR)¶
This class implements the Serializable
interface
and its superclass does not. When such an object is deserialized,
the fields of the superclass need to be initialized by
invoking the void constructor of the superclass.
Since the superclass does not have one,
serialization and deserialization will fail at runtime.
Se: Externalizable ãªã‚¯ãƒ©ã‚¹ãŒå¼•æ•°ãªã—コンストラクタを定義ã—ã¦ã„ãªã„ (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)¶
This class implements the Externalizable
interface, but does
not define a void constructor. When Externalizable objects are deserialized,
they first need to be constructed by invoking the void
constructor. Since this class does not have one,
serialization and deserialization will fail at runtime.
Se: Comparator 㯠Serializable を実装ã—ã¦ã„ãªã„ (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)¶
This class implements the Comparator
interface. You
should consider whether or not it should also implement the Serializable
interface. If a comparator is used to construct an ordered collection
such as a TreeMap
, then the TreeMap
will be serializable only if the comparator is also serializable.
As most comparators have little or no state, making them serializable
is generally easy and good defensive programming.
SnVI: Serializable ãªã‚¯ãƒ©ã‚¹ãŒ serialVersionUID を定義ã—ã¦ã„ãªã„ (SE_NO_SERIALVERSIONID)¶
This class implements the Serializable
interface, but does
not define a serialVersionUID
field.
A change as simple as adding a reference to a .class object
will add synthetic fields to the class,
which will unfortunately change the implicit
serialVersionUID (e.g., adding a reference to String.class
will generate a static field class$java$lang$String
).
Also, different source code to bytecode compilers may use different
naming conventions for synthetic variables generated for
references to class objects or inner classes.
To ensure interoperability of Serializable across versions,
consider adding an explicit serialVersionUID.
Se: readResolve メソッドã®æˆ»ã‚Šå€¤ã®åž‹ãŒ Object ã§å®£è¨€ã•ã‚Œã¦ã„ãªã„ (SE_READ_RESOLVE_MUST_RETURN_OBJECT)¶
In order for the readResolve method to be recognized by the serialization mechanism, it must be declared to have a return type of Object.
Se: 直列化復元ã«ã‚ˆã£ã¦è¨å®šã•ã‚Œãªã„ transient フィールド (SE_TRANSIENT_FIELD_NOT_RESTORED)¶
This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deserialized instance of the class.
Se: serialVersionUID ㌠final ã§ã¯ãªã„ (SE_NONFINAL_SERIALVERSIONID)¶
This class defines a serialVersionUID
field that is not final.
The field should be made final
if it is intended to specify
the version UID for purposes of serialization.
Se: serialVersionUID ㌠static ã§ã¯ãªã„ (SE_NONSTATIC_SERIALVERSIONID)¶
This class defines a serialVersionUID
field that is not static.
The field should be made static
if it is intended to specify
the version UID for purposes of serialization.
Se: serialVersionUID ㌠long ã§ã¯ãªã„ (SE_NONLONG_SERIALVERSIONID)¶
This class defines a serialVersionUID
field that is not long.
The field should be made long
if it is intended to specify
the version UID for purposes of serialization.
Se: 直列化å¯èƒ½ã‚¯ãƒ©ã‚¹ã®éž transient ã§éžç›´åˆ—化å¯èƒ½ãªã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (SE_BAD_FIELD)¶
This Serializable class defines a non-primitive instance field which is neither transient,
Serializable, or java.lang.Object
, and does not appear to implement
the Externalizable
interface or the
readObject()
and writeObject()
methods.
Objects of this class will not be deserialized correctly if a non-Serializable
object is stored in this field.
Se: 直列化å¯èƒ½ãªå†…部クラス (SE_INNER_CLASS)¶
This Serializable class is an inner class. Any attempt to serialize it will also serialize the associated outer instance. The outer instance is serializable, so this won't fail, but it might serialize a lot more data than intended. If possible, making the inner class a static inner class (also known as a nested class) should solve the problem.
Se: éžç›´åˆ—化å¯èƒ½ã‚¯ãƒ©ã‚¹ã«ç›´åˆ—化å¯èƒ½ãªå†…部クラスãŒã‚ã‚‹ (SE_BAD_FIELD_INNER_CLASS)¶
This Serializable class is an inner class of a non-serializable class. Thus, attempts to serialize it will also attempt to associate instance of the outer class with which it is associated, leading to a runtime error.
If possible, making the inner class a static inner class should solve the problem. Making the outer class serializable might also work, but that would mean serializing an instance of the inner class would always also serialize the instance of the outer class, which it often not what you really want.
Se: éžç›´åˆ—化å¯èƒ½ãªå€¤ã‚’直列化å¯èƒ½ã‚¯ãƒ©ã‚¹ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã«æ ¼ç´ã—ã¦ã„ã‚‹ (SE_BAD_FIELD_STORE)¶
A non-serializable value is stored into a non-transient field of a serializable class.
RV: 例外的戻り値を無視ã—ã¦ã„るメソッド (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)¶
This method returns a value that is not checked. The return value should be checked
since it can indicate an unusual or unexpected function execution. For
example, the File.delete()
method returns false
if the file could not be successfully deleted (rather than
throwing an Exception).
If you don't check the result, you won't notice if the method invocation
signals unexpected behavior by returning an atypical return value.
NP: null ã‚’è¿”ã™ã‹ã‚‚ã—ã‚Œãªã„ toString メソッド (NP_TOSTRING_COULD_RETURN_NULL)¶
This toString method seems to return null in some circumstances. A liberal reading of the spec could be interpreted as allowing this, but it is probably a bad idea and could cause other code to break. Return the empty string or some other appropriate string rather than null.
NP: null ã‚’è¿”ã™ã‹ã‚‚ã—ã‚Œãªã„ clone メソッド (NP_CLONE_COULD_RETURN_NULL)¶
This clone method seems to return null in some circumstances, but clone is never allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError instead.
OS: ストリームã®ã‚¯ãƒãƒ¼ã‚ºã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (OS_OPEN_STREAM)¶
The method creates an IO stream object, does not assign it to any
fields, pass it to other methods that might close it,
or return it, and does not appear to close
the stream on all paths out of the method. This may result in
a file descriptor leak. It is generally a good
idea to use a finally
block to ensure that streams are
closed.
OS: 例外経路ã§ã‚¹ãƒˆãƒªãƒ¼ãƒ ã®ã‚¯ãƒãƒ¼ã‚ºã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (OS_OPEN_STREAM_EXCEPTION_PATH)¶
The method creates an IO stream object, does not assign it to any
fields, pass it to other methods, or return it, and does not appear to close
it on all possible exception paths out of the method.
This may result in a file descriptor leak. It is generally a good
idea to use a finally
block to ensure that streams are
closed.
RC: 定数ã®ç–‘ã‚ã—ã„å‚照比較 (RC_REF_COMPARISON_BAD_PRACTICE)¶
This method compares a reference value to a constant using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.
RC: Boolean 値ã®ç–‘ã‚ã—ã„å‚照比較 (RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN)¶
This method compares two Boolean values using the == or != operator.
Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE),
but it is possible to create other Boolean objects using the new Boolean(b)
constructor. It is best to avoid such objects, but if they do exist,
then checking Boolean objects for equality using == or != will give results
than are different than you would get using .equals(...)
.
FS: Format string should use %n rather than n (VA_FORMAT_STRING_USES_NEWLINE)¶
This format string includes a newline character (\n). In format strings, it is generally preferable to use %n, which will produce the platform-specific line separator.
BIT: ビット演算ã®ç¬¦å·ã‚’ãƒã‚§ãƒƒã‚¯ã™ã‚‹ (BIT_SIGNED_CHECK)¶
This method compares an expression such as
((event.detail & SWT.SELECTED) > 0)
.
Using bit arithmetic and then comparing with the greater than operator can
lead to unexpected results (of course depending on the value of
SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate
for a bug. Even when SWT.SELECTED is not negative, it seems good practice
to use '!= 0' instead of '> 0'.
ODR: データベースリソースã®ã‚¯ãƒãƒ¼ã‚ºã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (ODR_OPEN_DATABASE_RESOURCE)¶
The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.
ODR: 例外経路ã§ãƒ‡ãƒ¼ã‚¿ãƒ™ãƒ¼ã‚¹ãƒªã‚½ãƒ¼ã‚¹ã®ã‚¯ãƒãƒ¼ã‚ºã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)¶
The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all exception paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.
ISC: static メソッドã ã‘ã‚’æä¾›ã™ã‚‹ã‚¯ãƒ©ã‚¹ã®ä¸å¿…è¦ãªã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹åŒ– (ISC_INSTANTIATE_STATIC_CLASS)¶
This class allocates an object that is based on a class that only supplies static methods. This object does not need to be created, just access the static methods directly using the class name as a qualifier.
DMI: Random オブジェクトãŒä½œæˆã•ã‚Œ1度ã—ã‹ä½¿ã‚ã‚Œãªã„ (DMI_RANDOM_USED_ONLY_ONCE)¶
This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required invoke a method on the existing Random object to obtain it.
If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead (and avoid allocating a new SecureRandom for each random number needed).
BC: equals メソッドã¯å¼•æ•°ã®åž‹ã‚’仮定ã™ã¹ãã§ã¯ãªã„ (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)¶
The equals(Object o)
method shouldn't make any assumptions
about the type of o
. It should simply return
false if o
is not the same type as this
.
J2EE: HttpSession ã¸ã®éžç›´åˆ—化å¯èƒ½ã‚ªãƒ–ジェクトã®æ ¼ç´ (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)¶
This code seems to be storing a non-serializable object into an HttpSession. If this session is passivated or migrated, an error will result.
GC: 検査ã•ã‚Œãªã„åž‹ã¸ã®ç·ç§°å‘¼ã³å‡ºã— (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)¶
This call to a generic collection method passes an argument while compile type Object where a specific type from the generic type parameters is expected. Thus, neither the standard Java type system nor static analysis can provide useful information on whether the object being passed as a parameter is of an appropriate type.
PZ: ç¹°ã‚Šè¿”ã—ã§ã‚¨ãƒ³ãƒˆãƒªã‚ªãƒ–ジェクトをå†åˆ©ç”¨ã—ãªã„ (PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS)¶
The entrySet() method is allowed to return a view of the
underlying Map in which an Iterator and Map.Entry. This clever
idea was used in several Map implementations, but introduces the possibility
of nasty coding mistakes. If a map m
returns
such an iterator for an entrySet, then
c.addAll(m.entrySet())
will go badly wrong. All of
the Map implementations in OpenJDK 1.7 have been rewritten to avoid this,
you should to.
DMI: エントリセットã®è¦ç´ ã‚’åŠ ãˆã‚‹ã“ã¨ã¯ï¼ŒEntry オブジェクトã®å†åˆ©ç”¨ã®ãŸã‚ã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„ (DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS)¶
The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.
DMI: コレクションを消去ã™ã‚‹ãŸã‚ã« removeAll メソッドを使用ã—ãªã„ (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)¶
If you want to remove all elements from a collection c
, use c.clear
,
not c.removeAll(c)
. Calling c.removeAll(c)
to clear a collection
is less clear, susceptible to errors from typos, less efficient and
for some collections, might throw a ConcurrentModificationException
.
æ£ç¢ºæ€§ (CORRECTNESS)¶
Probable bug - an apparent coding mistake resulting in code that was probably not what the developer intended. We strive for a low false positive rate.
NP: Optional ã®æˆ»ã‚Šåž‹ã‚’æŒã¤ãƒ¡ã‚½ãƒƒãƒ‰ãŒæ˜Žç¤ºçš„ã« null を返㙠(NP_OPTIONAL_RETURN_NULL)¶
The usage of Optional return type (java.util.Optional or com.google.common.base.Optional) always means that explicit null returns were not desired by design. Returning a null value in such case is a contract violation and will most likely break client code.
NP: éž null フィールドã¯åˆæœŸåŒ–ã•ã‚Œã¦ã„ãªã„ (NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)¶
The field is marked as non-null, but isn't written to by the constructor. The field might be initialized elsewhere during constructor, or might always be initialized before use.
VR: 解決ã§ããªã„クラス,メソッドã¸ã®å‚ç…§ (VR_UNRESOLVABLE_REFERENCE)¶
This class makes a reference to a class or method that can not be resolved using against the libraries it is being analyzed with.
IL: 明らã‹ãªç„¡é™ãƒ«ãƒ¼ãƒ— (IL_INFINITE_LOOP)¶
This loop doesn't seem to have a way to terminate (other than by perhaps throwing an exception).
IO: オブジェクト出力ストリームã¸ã®è¿½åŠ ã¯å¤±æ•—ã«çµ‚ã‚ã‚‹ (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)¶
This code opens a file in append mode and then wraps the result in an object output stream. This won't allow you to append to an existing object output stream stored in a file. If you want to be able to append to an object output stream, you need to keep the object output stream open.
The only situation in which opening a file in append mode and the writing an object output stream could work is if on reading the file you plan to open it in random access mode and seek to the byte offset where the append started.
TODO: example.
IL: 明らã‹ãªç„¡é™å†å¸°ãƒ«ãƒ¼ãƒ— (IL_INFINITE_RECURSIVE_LOOP)¶
This method unconditionally invokes itself. This would seem to indicate an infinite recursive loop that will result in a stack overflow.
IL: コレクションã¯è‡ªåˆ†è‡ªèº«ã‚’è¿½åŠ ã—ã¦ã„ã‚‹ (IL_CONTAINER_ADDED_TO_ITSELF)¶
A collection is added to itself. As a result, computing the hashCode of this set will throw a StackOverflowException.
RpC: æ¡ä»¶ãƒ†ã‚¹ãƒˆã®ç¹°ã‚Šè¿”ã— (RpC_REPEATED_CONDITIONAL_TEST)¶
The code contains a conditional test is performed twice, one right after the other
(e.g., x == 0 || x == 0
). Perhaps the second occurrence is intended to be something else
(e.g., x == 0 || y == 0
).
FL: 浮動å°æ•°ç‚¹ç²¾åº¦ã‚’使用ã—ãŸè¨ˆç®—ã‚’ã—ã¦ã„ã‚‹ (FL_MATH_USING_FLOAT_PRECISION)¶
The method performs math operations using floating point precision. Floating point precision is very imprecise. For example, 16777216.0f + 1.0f = 16777216.0f. Consider using double math instead.
CAA: ãŠãら互æ›æ€§ã®ãªã„è¦ç´ ã‚’ã共変é…列ã«æ ¼ç´ã—ã¦ã„ã‚‹ (CAA_COVARIANT_ARRAY_ELEMENT_STORE)¶
Value is stored into the array and the value type doesn't match the array type. It's known from the analysis that actual array type is narrower than the declared type of its variable or field and this assignment doesn't satisfy the original array type. This assignment may cause ArrayStoreException at runtime.
Dm: EasyMock メソッドã¸ã®å½¹ã«ç«‹ãŸãªã„/ç„¡æ„味ãªå‘¼ã³å‡ºã— (DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD)¶
This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything.
Dm: ScheduledThreadPoolExecutor ã®æœ€å¤§ãƒ—ールサイズを変ãˆã‚ˆã†ã¨ã™ã‚‹ç„¡é§„ãªè©¦ã¿ (DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR)¶
(Javadoc) While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect.
DMI: æ£ç¢ºã«è¡¨ã•ã‚Œãªã„ double ã‹ã‚‰æ§‹ç¯‰ã•ã‚ŒãŸ BigDecimal (DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE)¶
This code creates a BigDecimal from a double value that doesn't translate well to a decimal number. For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1).
Dm: コアプールサイズãŒ0ã® ScheduledThreadPoolExecutor ã®ä½œæˆ (DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS)¶
(Javadoc) A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored.
Dm: ランタイムリテンションãªã—ã§ï¼Œã‚¢ãƒŽãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å˜åœ¨ã‚’調ã¹ã‚‹ãŸã‚ã«ãƒªãƒ•ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ã‚’使用ã™ã‚‹ã“ã¨ã¯ã§ããªã„ (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)¶
Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection (e.g., by using the isAnnotationPresent method). .
NP: null ã®å¼•æ•°ã‚’ãƒã‚§ãƒƒã‚¯ã—ã¦ã„ãªã„メソッド (NP_ARGUMENT_MIGHT_BE_NULL)¶
A parameter to this method has been identified as a value that should always be checked to see whether or not it is null, but it is being dereferenced without a preceding null check.
RV: 符å·ä»˜ãæ•´æ•°ã®ä¹±æ•°ã®çµ¶å¯¾å€¤ã‚’計算ã™ã‚‹é–“é•ã£ãŸè©¦ã¿ (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)¶
This code generates a random signed integer and then computes
the absolute value of that random integer. If the number returned by the random number
generator is Integer.MIN_VALUE
, then the result will be negative as well (since
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
). (Same problem arises for long values as well).
RV: 符å·ä»˜ã32ビットãƒãƒƒã‚·ãƒ¥ã‚³ãƒ¼ãƒ‰ã®çµ¶å¯¾å€¤ã‚’計算ã™ã‚‹é–“é•ã£ãŸè©¦ã¿ (RV_ABSOLUTE_VALUE_OF_HASHCODE)¶
This code generates a hashcode and then computes
the absolute value of that hashcode. If the hashcode
is Integer.MIN_VALUE
, then the result will be negative as well (since
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
).
One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES".
RV: 0ã‹ã‚‰1ã®ä¹±æ•°å€¤ã¯æ•´æ•°å€¤0ã«ä¸¸ã‚られる (RV_01_TO_INT)¶
A random value from 0 to 1 is being coerced to the integer value 0. You probably
want to multiply the random value by something else before coercing it to an integer, or use the Random.nextInt(n)
method.
Dm: Math.max 㨠Math.min ã®é–“é•ã£ãŸçµ„ã¿åˆã‚ã› (DM_INVALID_MIN_MAX)¶
This code tries to limit the value bounds using the construct like Math.min(0, Math.max(100, value)). However the order of the constants is incorrect: it should be Math.min(100, Math.max(0, value)). As the result this code always produces the same result (or NaN if the value is NaN).
Eq: equals メソッドã¯ã‚¯ãƒ©ã‚¹ã‚ªãƒ–ジェクトã§ã¯ãªãクラスåを比較ã—ã¦ã„ã‚‹ (EQ_COMPARING_CLASS_NAMES)¶
This method checks to see if two objects are the same class by checking to see if the names of their classes are equal. You can have different classes with the same name if they are loaded by different class loaders. Just check to see if the class objects are the same.
Eq: equals メソッドã¯å¸¸ã« true を返㙠(EQ_ALWAYS_TRUE)¶
This class defines an equals method that always returns true. This is imaginative, but not very smart. Plus, it means that the equals method is not symmetric.
Eq: equals メソッドã¯å¸¸ã« false を戻㙠(EQ_ALWAYS_FALSE)¶
This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means that equals is not reflexive, one of the requirements of the equals method.
The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class Object
. If you need to override an equals inherited from a different
superclass, you can use:
public boolean equals(Object o) {
return this == o;
}
Eq: equals メソッドã¯ã‚¹ãƒ¼ãƒ‘ークラス㮠equals メソッドをオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ã‚‹ãŒï¼Œå¯¾ç§°çš„ã§ã¯ãªã„ã‹ã‚‚ã—ã‚Œãªã„ (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)¶
This class defines an equals method that overrides an equals method in a superclass. Both equals methods
methods use instanceof
in the determination of whether two objects are equal. This is fraught with peril,
since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)
).
If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method
checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these
methods is not symmetric.
Eq: 列挙型ã¯å…±å¤‰ãª equals メソッドを定義ã—ã¦ã„ã‚‹ (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)¶
This class defines an enumeration, and equality on enumerations are defined using object identity. Defining a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don't do it.
Eq: 共変㪠equals メソッドを定義ã—ã¦ï¼ŒObject.equals(Object) を継承ã—ã¦ã„ã‚‹ (EQ_SELF_USE_OBJECT)¶
This class defines a covariant version of the equals()
method, but inherits the normal equals(Object)
method
defined in the base java.lang.Object
class.
The class should probably define a boolean equals(Object)
method.
Eq: Object.equals(Object) をオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ãªã„ equals メソッドã®å®šç¾© (EQ_OTHER_USE_OBJECT)¶
This class defines an equals()
method, that doesn't override the normal equals(Object)
method
defined in the base java.lang.Object
class.
The class should probably define a boolean equals(Object)
method.
Eq: equals(Object) メソッドをオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ãªã„ equals メソッドã®å®šç¾© (EQ_OTHER_NO_OBJECT)¶
This class defines an equals()
method, that doesn't override the normal equals(Object)
method
defined in the base java.lang.Object
class. Instead, it
inherits an equals(Object)
method from a superclass.
The class should probably define a boolean equals(Object)
method.
HE: ãƒãƒƒã‚·ãƒ¥åŒ–ã•ã‚ŒãŸã‚³ãƒ³ãƒ†ã‚ストã§ãƒãƒƒã‚·ãƒ¥åŒ–ã§ããªã„クラスã®ä½¿ç”¨ãŒã‚·ã‚°ãƒãƒãƒ£ã§å®£è¨€ã•ã‚Œã¦ã„ã‚‹ (HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS)¶
A method, field or class declares a generic signature where a non-hashable class is used in context where a hashable class is required. A class that declares an equals method but inherits a hashCode() method from Object is unhashable, since it doesn't fulfill the requirement that equal objects have equal hashCodes.
HE: ãƒãƒƒã‚·ãƒ¥ãƒ‡ãƒ¼ã‚¿æ§‹é€ 㧠hashCode メソッドã®ãªã„クラスを使用ã—ã¦ã„ã‚‹ (HE_USE_OF_UNHASHABLE_CLASS)¶
A class defines an equals(Object) method but not a hashCode() method, and thus doesn't fulfill the requirement that equal objects have equal hashCodes. An instance of this class is used in a hash data structure, making the need to fix this problem of highest importance.
UR: コンストラクタã§åˆæœŸåŒ–ã•ã‚Œã¦ã„ãªã„フィールドをèªã¿å‡ºã—ã¦ã„ã‚‹ (UR_UNINIT_READ)¶
This constructor reads a field which has not yet been assigned a value. This is often caused when the programmer mistakenly uses the field instead of one of the constructor's parameters.
UR: スーパークラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‹ã‚‰å‘¼ã³å‡ºã•ã‚Œã‚‹ãƒ¡ã‚½ãƒƒãƒ‰ã§åˆæœŸåŒ–ã•ã‚Œã¦ã„ãªã„フィールドをèªã¿å‡ºã—ã¦ã„ã‚‹ (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)¶
This method is invoked in the constructor of the superclass. At this point, the fields of the class have not yet initialized.
To make this more concrete, consider the following classes:
abstract class A {
int hashCode;
abstract Object getValue();
A() {
hashCode = getValue().hashCode();
}
}
class B extends A {
Object value;
B(Object v) {
this.value = v;
}
Object getValue() {
return value;
}
}
When a B
is constructed,
the constructor for the A
class is invoked
before the constructor for B
sets value
.
Thus, when the constructor for A
invokes getValue
,
an uninitialized value is read for value
.
Nm: éžå¸¸ã«ç´›ã‚‰ã‚ã—ã„åå‰ã®ãƒ¡ã‚½ãƒƒãƒ‰ (NM_VERY_CONFUSING)¶
The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other.
Nm: パラメータã®é–“é•ã£ãŸãƒ‘ッケージã®ãŸã‚ã«ã‚¹ãƒ¼ãƒ‘ークラスã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’オーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ãªã„メソッド (NM_WRONG_PACKAGE)¶
The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:
import alpha.Foo;
public class A {
public int f(Foo x) { return 17; }
}
----
import beta.Foo;
public class B extends A {
public int f(Foo x) { return 42; }
}
The f(Foo)
method defined in class B
doesn't
override the
f(Foo)
method defined in class A
, because the argument
types are Foo
's from different packages.
Nm: 明らã‹ãªãƒ¡ã‚½ãƒƒãƒ‰ã¨ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã®æ··ä¹± (NM_METHOD_CONSTRUCTOR_CONFUSION)¶
This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. If it was intended to be a constructor, remove the declaration of a void return value. If you had accidentally defined this method, realized the mistake, defined a proper constructor but can't get rid of this method due to backwards compatibility, deprecate the method.
Nm: クラス㯠hashcode() を定義ã—ã¦ã„ã¾ã™ã€‚hashCode() ã«ã™ã¹ãã§ã™ã‹? (NM_LCASE_HASHCODE)¶
This class defines a method called hashcode()
. This method
does not override the hashCode()
method in java.lang.Object
,
which is probably what was intended.
Nm: クラス㯠tostring() を定義ã—ã¦ã„ã¾ã™ã€‚toString() ã«ã™ã¹ãã§ã™ã‹? (NM_LCASE_TOSTRING)¶
This class defines a method called tostring()
. This method
does not override the toString()
method in java.lang.Object
,
which is probably what was intended.
Nm: クラス㯠equal(Object) を定義ã—ã¦ã„ã¾ã™ã€‚equals(Object) ã«ã™ã¹ãã§ã™ã‹? (NM_BAD_EQUAL)¶
This class defines a method equal(Object)
. This method does
not override the equals(Object)
method in java.lang.Object
,
which is probably what was intended.
Se: readResolve メソッド㌠static メソッドã¨ã—ã¦å®£è¨€ã•ã‚Œã¦ã„ã‚‹ (SE_READ_RESOLVE_IS_STATIC)¶
In order for the readResolve method to be recognized by the serialization mechanism, it must not be declared as a static method.
Se: 直列化機構ã®ãŸã‚ã« private ã«ã—ãªã‘ã‚Œã°ãªã‚‰ãªã„メソッド (SE_METHOD_MUST_BE_PRIVATE)¶
This class implements the Serializable
interface, and defines a method
for custom serialization/deserialization. But since that method isn't declared private,
it will be silently ignored by the serialization/deserialization API.
SF: switch æ–‡ã®ãƒ•ã‚©ãƒ¼ãƒ«ã‚¹ãƒ«ãƒ¼ã®ãŸã‚ã«æ ¼ç´ãŒç„¡åŠ¹ã«ãªã£ã¦ã„ã‚‹ (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)¶
A value stored in the previous switch case is overwritten here due to a switch fall through. It is likely that you forgot to put a break or return at the end of the previous case.
SF: スãƒãƒ¼ã™ã‚‹ switch æ–‡ã®ãƒ•ã‚©ãƒ¼ãƒ«ã‚¹ãƒ«ãƒ¼ã®ãŸã‚ã«æ ¼ç´ãŒç„¡åŠ¹ã«ãªã£ã¦ã„ã‚‹ (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW)¶
A value stored in the previous switch case is ignored here due to a switch fall through to a place where an exception is thrown. It is likely that you forgot to put a break or return at the end of the previous case.
NP: 書ãè¾¼ã¾ã‚Œã¦ã„ãªã„フィールドã®èªã¿å‡ºã— (NP_UNWRITTEN_FIELD)¶
The program is dereferencing a field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.
UwF: null ã«è¨å®šã•ã‚Œã‚‹ã ã‘ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (UWF_NULL_FIELD)¶
All writes to this field are of the constant value null, and thus all reads of the field will return null. Check for errors, or remove it if it is useless.
UwF: 書ãè¾¼ã¾ã‚Œã¦ã„ãªã„フィールド (UWF_UNWRITTEN_FIELD)¶
This field is never written. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.
SIC: éž static 内部クラスã¨ã‚¹ãƒ¬ãƒƒãƒ‰ãƒãƒ¼ã‚«ãƒ«ã®ãƒ‡ãƒƒãƒ‰ãƒãƒƒã‚¯ (SIC_THREADLOCAL_DEADLY_EMBRACE)¶
This class is an inner class, but should probably be a static inner class. As it is, there is a serious danger of a deadly embrace between the inner class and the thread local in the outer class. Because the inner class isn't static, it retains a reference to the outer class. If the thread local contains a reference to an instance of the inner class, the inner and outer instance will both be reachable and not eligible for garbage collection.
RANGE: é…列インデックスã¯ç¯„囲外 (RANGE_ARRAY_INDEX)¶
Array operation is performed, but array index is out of bounds, which will result in ArrayIndexOutOfBoundsException at runtime.
RANGE: é…列オフセットã¯ç¯„囲外 (RANGE_ARRAY_OFFSET)¶
Method is called with array parameter and offset parameter, but the offset is out of bounds. This will result in IndexOutOfBoundsException at runtime.
RANGE: é…列ã®é•·ã•ã¯ç¯„囲外 (RANGE_ARRAY_LENGTH)¶
Method is called with array parameter and length parameter, but the length is out of bounds. This will result in IndexOutOfBoundsException at runtime.
RANGE: æ–‡å—列インデックスã¯ç¯„囲外 (RANGE_STRING_INDEX)¶
String method is called and specified string index is out of bounds. This will result in StringIndexOutOfBoundsException at runtime.
RV: 戻り値を無視ã—ã¦ã„るメソッド (RV_RETURN_VALUE_IGNORED)¶
The return value of this method should be checked. One common cause of this warning is to invoke a method on an immutable object, thinking that it updates the object. For example, in the following code fragment,
String dateString = getHeaderField(name);
dateString.trim();
the programmer seems to be thinking that the trim() method will update the String referenced by dateString. But since Strings are immutable, the trim() function returns a new String value, which is being ignored here. The code should be corrected to:
String dateString = getHeaderField(name);
dateString = dateString.trim();
RV: 作æˆã—ãŸä¾‹å¤–をスãƒãƒ¼ã™ã‚‹ã®ã§ã¯ãªãæ¨ã¦ã¦ã„ã‚‹ (RV_EXCEPTION_NOT_THROWN)¶
This code creates an exception (or error) object, but doesn't do anything with it. For example, something like
if (x < 0) {
new IllegalArgumentException("x must be nonnegative");
}
It was probably the intent of the programmer to throw the created exception:
if (x < 0) {
throw new IllegalArgumentException("x must be nonnegative");
}
RV: compareTo ã«ã‚ˆã£ã¦è¿”ã•ã‚ŒãŸç‰¹å®šã®å€¤ã®ã‚³ãƒ¼ãƒ‰ãƒã‚§ãƒƒã‚¯ (RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE)¶
This code invoked a compareTo or compare method, and checks to see if the return value is a specific value, such as 1 or -1. When invoking these methods, you should only check the sign of the result, not for any specific non-zero value. While many or most compareTo and compare methods only return -1, 0 or 1, some of them will return other values.
NP: null 値を利用ã—ã¦ã„ã‚‹ (NP_ALWAYS_NULL)¶
A null pointer is dereferenced here. This will lead to a
NullPointerException
when the code is executed.
NP: 常㫠null 値ã®ã‚ªãƒ–ジェクト㧠close メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (NP_CLOSING_NULL)¶
close() is being invoked on a value that is always null. If this statement is executed, a null pointer exception will occur. But the big risk here you never close something that should be closed.
NP: @Nonnull アノテーションãŒä»˜ã‘られãŸãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã« null ã‚’æ ¼ç´ã—ã¦ã„ã‚‹ (NP_STORE_INTO_NONNULL_FIELD)¶
A value that could be null is stored into a field that has been annotated as @Nonnull.
NP: null 値を例外経路ã§åˆ©ç”¨ã—ã¦ã„ã‚‹ (NP_ALWAYS_NULL_EXCEPTION)¶
A pointer which is null on an exception path is dereferenced here.
This will lead to a NullPointerException
when the code is executed.
Note that because SpotBugs currently does not prune infeasible exception paths,
this may be a false warning.
Also note that SpotBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.
NP: null 値を利用ã—ã¦ã„ã‚‹å¯èƒ½æ€§ãŒã‚ã‚‹ (NP_NULL_ON_SOME_PATH)¶
There is a branch of statement that, if executed, guarantees that
a null value will be dereferenced, which
would generate a NullPointerException
when the code is executed.
Of course, the problem might be that the branch or statement is infeasible and that
the null pointer exception can't ever be executed; deciding that is beyond the ability of SpotBugs.
NP: null 値を例外経路ã§åˆ©ç”¨ã—ã¦ã„ã‚‹å¯èƒ½æ€§ãŒã‚ã‚‹ (NP_NULL_ON_SOME_PATH_EXCEPTION)¶
A reference value which is null on some exception control path is
dereferenced here. This may lead to a NullPointerException
when the code is executed.
Note that because SpotBugs currently does not prune infeasible exception paths,
this may be a false warning.
Also note that SpotBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.
NP: メソッド呼ã³å‡ºã—ã¯éž null パラメータ㫠null を渡ã—ã¦ã„ã‚‹ (NP_NULL_PARAM_DEREF)¶
This method call passes a null value for a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.
NP: éž null パラメータ㫠null を渡ã—ã¦ã„ã‚‹éžä»®æƒ³ãƒ¡ã‚½ãƒƒãƒ‰ã®å‘¼ã³å‡ºã— (NP_NULL_PARAM_DEREF_NONVIRTUAL)¶
A possibly-null value is passed to a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.
NP: メソッド呼ã³å‡ºã—ã¯éž null パラメータ㫠null を渡ã—ã¦ã„ã‚‹ (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)¶
A possibly-null value is passed at a call site where all known target methods require the parameter to be non-null. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.
NP: メソッド呼ã³å‡ºã—ã¯éž null パラメータ㫠null を渡ã—ã¦ã„ã‚‹ (NP_NONNULL_PARAM_VIOLATION)¶
This method passes a null value as the parameter of a method which must be non-null. Either this parameter has been explicitly marked as @Nonnull, or analysis has determined that this parameter is always dereferenced.
NP: null ã‚’è¿”ã™ã‹ã‚‚ã—ã‚Œãªã„メソッド㌠@Nonnull 宣言ã•ã‚Œã¦ã„ã‚‹ (NP_NONNULL_RETURN_VIOLATION)¶
This method may return a null value, but the method (or a superclass method which it overrides) is declared to return @Nonnull.
NP: null 値を利用ã™ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã¦ã„ã‚‹ (NP_GUARANTEED_DEREF)¶
There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).
Note that a check such as
if (x == null) throw new NullPointerException();
is treated as a dereference of x
.
NP: null 値を例外経路ã§åˆ©ç”¨ã™ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã¦ã„ã‚‹ (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)¶
There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).
DMI: 逆ã«ã•ã‚ŒãŸãƒ¡ã‚½ãƒƒãƒ‰å¼•æ•° (DMI_ARGUMENTS_WRONG_ORDER)¶
The arguments to this method call seem to be in the wrong order.
For example, a call Preconditions.checkNotNull("message", message)
has reserved arguments: the value to be checked is the first argument.
RCN: æ—¢ã«åˆ©ç”¨ã—ã¦ã„ãŸå€¤ã® null ãƒã‚§ãƒƒã‚¯ (RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)¶
A value is checked here to see whether it is null, but this value can't be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference. Essentially, this code and the previous dereference disagree as to whether this value is allowed to be null. Either the check is redundant or the previous dereference is erroneous.
RC: ç–‘ã‚ã—ã„å‚照比較 (RC_REF_COMPARISON)¶
This method compares two reference values using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.
VA: å¯å¤‰é•·å¼•æ•°ã‚’期待ã—ã¦ã„るメソッドã«ãƒ—リミティブ型ã®é…列を渡ã—ã¦ã„ã‚‹ (VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG)¶
This code passes a primitive array to a function that takes a variable number of object arguments. This creates an array of length one to hold the primitive array and passes it to the function.
FS: 与ãˆã‚‰ã‚ŒãŸå¼•æ•°ã®åž‹ã¯æ›¸å¼æŒ‡ç¤ºåã«åˆè‡´ã—ãªã„ (VA_FORMAT_STRING_BAD_CONVERSION)¶
One of the arguments is incompatible with the corresponding format string specifier.
As a result, this will generate a runtime exception when executed.
For example, String.format("%d", "1")
will generate an exception, since
the String "1" is incompatible with the format specifier %d.
USELESS_STRING: 書å¼æ–‡å—列を使用ã—ã¦å½¹ã«ç«‹ãŸãªã„方法ã§é…列をフォーマットã—ã¦ã„ã‚‹ (VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY)¶
One of the arguments being formatted with a format string is an array. This will be formatted
using a fairly useless format, such as [I@304282, which doesn't actually show the contents
of the array.
Consider wrapping the array using Arrays.asList(...)
before handling it off to a formatted.
FS: 書å¼æ–‡å—列ãŸã‚ã®å‰ã®å¼•æ•°ãŒãªã„ (VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT)¶
The format string specifies a relative index to request that the argument for the previous format specifier be reused. However, there is no previous argument. For example,
formatter.format("%<s %s", "a", "b")
would throw a MissingFormatArgumentException when executed.
FS: 書å¼æ–‡å—列ã¸ã®å¼•æ•°ã®æ•°ã¨æ›¸å¼æŒ‡ç¤ºåã®æ•°ãŒä¸€è‡´ã—ã¦ã„ãªã„ (VA_FORMAT_STRING_ARG_MISMATCH)¶
A format-string method with a variable number of arguments is called, but the number of arguments passed does not match with the number of % placeholders in the format string. This is probably not what the author intended.
FS: 書å¼æŒ‡ç¤ºåã¸æ¸¡ã—ã¦ã„る引数ã«äº’æ›æ€§ãŒãªã„ (VA_FORMAT_STRING_BAD_ARGUMENT)¶
The format string placeholder is incompatible with the corresponding
argument. For example,
System.out.println("%d\n", "hello");
The %d placeholder requires a numeric argument, but a string value is passed instead. A runtime exception will occur when this statement is executed.
FS: 書å¼æ–‡å—列ã¯è¶³ã‚Šãªã„引数をå‚ç…§ã—ã¦ã„ã‚‹ (VA_FORMAT_STRING_MISSING_ARGUMENT)¶
Not enough arguments are passed to satisfy a placeholder in the format string. A runtime exception will occur when this statement is executed.
FS: 無効ãªæ›¸å¼æ–‡å—列 (VA_FORMAT_STRING_ILLEGAL)¶
The format string is syntactically invalid, and a runtime exception will occur when this statement is executed.
FS: 書å¼æ–‡å—列ã§å®Ÿéš›ã«ä½¿ã‚れるよりも多ãã®å¼•æ•°ãŒæ¸¡ã•ã‚Œã¦ã„ã‚‹ (VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED)¶
A format-string method with a variable number of arguments is called, but more arguments are passed than are actually used by the format string. This won't cause a runtime exception, but the code may be silently omitting information that was intended to be included in the formatted string.
FS: printf スタイルã®æ›¸å¼ãŒæœŸå¾…ã•ã‚Œã¦ã„ã‚‹ã¨ã“ã‚㧠MessageFormat ãŒä¸Žãˆã‚‰ã‚Œã¦ã„ã‚‹ (VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED)¶
A method is called that expects a Java printf format string and a list of arguments. However, the format string doesn't contain any format specifiers (e.g., %s) but does contain message format elements (e.g., {0}). It is likely that the code is supplying a MessageFormat string when a printf-style format string is required. At runtime, all of the arguments will be ignored and the format string will be returned exactly as provided without any formatting.
EC: equals メソッドを使用ã—ã¦é…列ã¨éžé…列を比較ã—ã¦ã„ã‚‹ (EC_ARRAY_AND_NONARRAY)¶
This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem to be an array. If things being compared are of different types, they are guaranteed to be unequal and the comparison is almost certainly an error. Even if they are both arrays, the equals method on arrays only determines of the two arrays are the same object. To compare the contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).
EC: equals(null) ã®å‘¼ã³å‡ºã— (EC_NULL_ARG)¶
This method calls equals(Object), passing a null value as
the argument. According to the contract of the equals() method,
this call should always return false
.
SA: フィールドã¸ã®ä»£å…¥ã§ã¯ãªããƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¸ã®è‡ªå·±ä»£å…¥ (SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD)¶
This method contains a self assignment of a local variable, and there is a field with an identical name. assignment appears to have been ; e.g.
int foo;
public void setFoo(int foo) {
foo = foo;
}
The assignment is useless. Did you mean to assign to the field instead?
INT: int 値㨠long 定数ã¨ã®é–“é•ã£ãŸæ¯”較 (INT_BAD_COMPARISON_WITH_INT_VALUE)¶
This code compares an int value with a long constant that is outside the range of values that can be represented as an int value. This comparison is vacuous and possibly to be incorrect.
INT: 符å·ä»˜ããƒã‚¤ãƒˆã®é–“é•ã£ãŸæ¯”較 (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)¶
Signed bytes can only have a value in the range -128 to 127. Comparing
a signed byte with a value outside that range is vacuous and likely to be incorrect.
To convert a signed byte b
to an unsigned value in the range 0..255,
use 0xff & b
.
INT: è² ã§ã¯ãªã„値ã¨è² ã®å®šæ•°ã¾ãŸã¯ã‚¼ãƒã¨ã®é–“é•ã£ãŸæ¯”較 (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)¶
This code compares a value that is guaranteed to be non-negative with a negative constant or zero.
BIT: 符å·ä»˜ããƒã‚¤ãƒˆå€¤ã®ãƒ“ãƒƒãƒˆåŠ ç®— (BIT_ADD_OF_SIGNED_BYTE)¶
Adds a byte value and a value which is known to have the 8 lower bits clear.
Values loaded from a byte array are sign extended to 32 bits
before any bitwise operations are performed on the value.
Thus, if b[0]
contains the value 0xff
, and
x
is initially 0, then the code
((x << 8) + b[0])
will sign extend 0xff
to get 0xffffffff
, and thus give the value
0xffffffff
as the result.
In particular, the following code for packing a byte array into an int is badly wrong:
int result = 0;
for(int i = 0; i < 4; i++)
result = ((result << 8) + b[i]);
The following idiom will work instead:
int result = 0;
for(int i = 0; i < 4; i++)
result = ((result << 8) + (b[i] & 0xff));
BIT: 符å·ä»˜ããƒã‚¤ãƒˆå€¤ã®ãƒ“ット論ç†å’Œ (BIT_IOR_OF_SIGNED_BYTE)¶
Loads a byte value (e.g., a value loaded from a byte array or returned by a method
with return type byte) and performs a bitwise OR with
that value. Byte values are sign extended to 32 bits
before any bitwise operations are performed on the value.
Thus, if b[0]
contains the value 0xff
, and
x
is initially 0, then the code
((x << 8) | b[0])
will sign extend 0xff
to get 0xffffffff
, and thus give the value
0xffffffff
as the result.
In particular, the following code for packing a byte array into an int is badly wrong:
int result = 0;
for(int i = 0; i < 4; i++) {
result = ((result << 8) | b[i]);
}
The following idiom will work instead:
int result = 0;
for(int i = 0; i < 4; i++) {
result = ((result << 8) | (b[i] & 0xff));
}
BIT: è² æ•°ã‚’å«ã‚€ãƒ“ット演算ã®ç¬¦å·ã‚’ãƒã‚§ãƒƒã‚¯ã™ã‚‹ (BIT_SIGNED_CHECK_HIGH_BIT)¶
This method compares a bitwise expression such as
((val & CONSTANT) > 0)
where CONSTANT is the negative number.
Using bit arithmetic and then comparing with the greater than operator can
lead to unexpected results. This comparison is unlikely to work as expected. The good practice is
to use '!= 0' instead of '> 0'.
BIT: 互æ›æ€§ã®ãªã„ビットマスク (BIT_AND)¶
This method compares an expression of the form (e & C) to D, which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.
BIT: ((...) & 0) == 0 ãªã®ã‹ç¢ºã‹ã‚ã¦ã„ã‚‹ (BIT_AND_ZZ)¶
This method compares an expression of the form (e & 0)
to 0,
which will always compare equal.
This may indicate a logic error or typo.
BIT: 互æ›æ€§ã®ãªã„ビットマスク (BIT_IOR)¶
This method compares an expression of the form (e | C)
to D.
which will always compare unequal
due to the specific values of constants C and D.
This may indicate a logic error or typo.
Typically, this bug occurs because the code wants to perform a membership test in a bit set, but uses the bitwise OR operator ("|") instead of bitwise AND ("&").
Also such bug may appear in expressions like (e & A | B) == C
which is parsed like ((e & A) | B) == C
while (e & (A | B)) == C
was intended.
SA: フィールドã®è‡ªå·±ä»£å…¥ (SA_FIELD_SELF_ASSIGNMENT)¶
This method contains a self assignment of a field; e.g.
int x;
public void foo() {
x = x;
}
Such assignments are useless, and may indicate a logic error or typo.
SA: フィールドã®ç„¡æ„味ãªè‡ªå·±æ¼”ç®— (ãŸã¨ãˆã°ï¼Œx & x) (SA_FIELD_SELF_COMPUTATION)¶
This method performs a nonsensical computation of a field with another reference to the same field (e.g., x&x or x-x). Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error. Double check the computation.
SA: 変数ã®ç„¡æ„味ãªè‡ªå·±æ¼”ç®— (ãŸã¨ãˆã°ï¼Œx & x) (SA_LOCAL_SELF_COMPUTATION)¶
This method performs a nonsensical computation of a local variable with another reference to the same variable (e.g., x&x or x-x). Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error. Double check the computation.
SA: フィールドã¨ãれ自身ã¨ã®è‡ªå·±æ¯”較 (SA_FIELD_SELF_COMPARISON)¶
This method compares a field with itself, and may indicate a typo or a logic error. Make sure that you are comparing the right things.
SA: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¨ãれ自身ã¨ã®è‡ªå·±æ¯”較 (SA_LOCAL_SELF_COMPARISON)¶
This method compares a local variable with itself, and may indicate a typo or a logic error. Make sure that you are comparing the right things.
UMAC: 呼ã³å‡ºã—ä¸å¯èƒ½ãªãƒ¡ã‚½ãƒƒãƒ‰ãŒç„¡åクラスã§å®šç¾©ã•ã‚Œã¦ã„ã‚‹ (UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)¶
This anonymous class defined a method that is not directly invoked and does not override a method in a superclass. Since methods in other classes cannot directly invoke methods declared in an anonymous class, it seems that this method is uncallable. The method might simply be dead code, but it is also possible that the method is intended to override a method declared in a superclass, and due to an typo or other error the method does not, in fact, override the method it is intended to.
IJU: run メソッドã§ã® JUnit アサーション㯠JUnit ã«ã‚ˆã£ã¦é€šçŸ¥ã•ã‚Œãªã„ (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)¶
A JUnit assertion is performed in a run method. Failed JUnit assertions just result in exceptions being thrown. Thus, if this exception occurs in a thread other than the thread that invokes the test method, the exception will terminate the thread but not result in the test failing.
IJU: TestCase 㯠suite メソッドã®é–“é•ã£ãŸå®£è¨€ã‚’ã—ã¦ã„ã‚‹ (IJU_BAD_SUITE_METHOD)¶
Class is a JUnit TestCase and defines a suite() method. However, the suite method needs to be declared as either
public static junit.framework.Test suite()
or
public static junit.framework.TestSuite suite()
IJU: TestCase 㯠super.setup() を呼ã³å‡ºã•ãªã„ setUp メソッドを実装ã—ã¦ã„ã‚‹ (IJU_SETUP_NO_SUPER)¶
Class is a JUnit TestCase and implements the setUp method. The setUp method should call super.setUp(), but doesn't.
IJU: TestCase 㯠super.tearDown() を呼ã³å‡ºã•ãªã„ tearDown メソッドを実装ã—ã¦ã„ã‚‹ (IJU_TEARDOWN_NO_SUPER)¶
Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call super.tearDown(), but doesn't.
IJU: TestCase ã¯ éž static 㪠suite メソッドを実装ã—ã¦ã„ã‚‹ (IJU_SUITE_NOT_STATIC)¶
Class is a JUnit TestCase and implements the suite() method. The suite method should be declared as being static, but isn't.
IJU: TestCase ã¯ãƒ†ã‚¹ãƒˆãŒãªã„ (IJU_NO_TESTS)¶
Class is a JUnit TestCase but has not implemented any test methods.
BOA: スーパークラス㮠Adapter ã§å®Ÿè£…ã•ã‚Œã‚‹ãƒ¡ã‚½ãƒƒãƒ‰ã‚’誤ã£ã¦ã‚ªãƒ¼ãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„るクラス (BOA_BADLY_OVERRIDDEN_ADAPTER)¶
This method overrides a method found in a parent class, where that class is an Adapter that implements a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not get called when the event occurs.
SQL: Method attempts to access a result set field with index 0 (BRSA_BAD_RESULTSET_ACCESS)¶
A call to getXXX or updateXXX methods of a result set was made where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.
SQL: インデックスãŒ0㧠ResultSet ã«ã‚¢ã‚¯ã‚»ã‚¹ã—よã†ã¨ã—ã¦ã„るメソッド (SQL_BAD_RESULTSET_ACCESS)¶
A call to getXXX or updateXXX methods of a result set was made where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.
SQL: インデックスãŒ0㧠PreparedStatement ã«ã‚¢ã‚¯ã‚»ã‚¹ã—よã†ã¨ã—ã¦ã„るメソッド (SQL_BAD_PREPARED_STATEMENT_ACCESS)¶
A call to a setXXX method of a prepared statement was made where the parameter index is 0. As parameter indexes start at index 1, this is always a mistake.
SIO: instanceof 演算åを使用ã—ãŸä¸å¿…è¦ãªåž‹ãƒã‚§ãƒƒã‚¯ (SIO_SUPERFLUOUS_INSTANCEOF)¶
Type check performed using the instanceof operator where it can be statically determined whether the object is of the type requested.
BAC: åˆæœŸåŒ–ã•ã‚Œã¦ã„ãªã„ AppletStub ã«ä¾å˜ã™ã‚‹é–“é•ã£ãŸã‚¢ãƒ—レットコンストラクタ (BAC_BAD_APPLET_CONSTRUCTOR)¶
This constructor calls methods in the parent Applet that rely on the AppletStub. Since the AppletStub isn't initialized until the init() method of this applet is called, these methods will not perform correctly.
EC: equals(...) メソッドを使用ã—ã¦äº’æ›æ€§ã®ãªã„é…列を比較ã—ã¦ã„ã‚‹ (EC_INCOMPATIBLE_ARRAY_COMPARE)¶
This method invokes the .equals(Object o) to compare two arrays, but the arrays of of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]). They will never be equal. In addition, when equals(...) is used to compare arrays it only checks to see if they are the same array, and ignores the contents of the arrays.
EC: é…列㮠equals メソッド呼ã³å‡ºã—㯠== ã¨ç‰ä¾¡ã§ã‚ã‚‹ (EC_BAD_ARRAY_COMPARE)¶
This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals
method of Object, calling equals on an array is the same as comparing their addresses. To compare the
contents of the arrays, use java.util.Arrays.equals(Object[], Object[])
.
To compare the addresses of the arrays, it would be
less confusing to explicitly check pointer equality using ==
.
STI: interrupted メソッドを呼ã³å‡ºã™ãŸã‚ã«ä¸è¦ãª currentThread メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (STI_INTERRUPTED_ON_CURRENTTHREAD)¶
This method invokes the Thread.currentThread() call, just to call the interrupted() method. As interrupted() is a static method, is more simple and clear to use Thread.interrupted().
STI: スレッドインスタンス㧠static Thread.interrupted() を呼ã³å‡ºã—ã¦ã„ã‚‹ (STI_INTERRUPTED_ON_UNKNOWNTHREAD)¶
This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is not the current thread. As the interrupted() method is static, the interrupted method will be called on a different object than the one the author intended.
DLS: return æ–‡ã«ç„¡é§„ãªã‚¤ãƒ³ã‚¯ãƒªãƒ¡ãƒ³ãƒˆãŒã‚ã‚‹ (DLS_DEAD_LOCAL_INCREMENT_IN_RETURN)¶
This statement has a return such as return x++;
.
A postfix increment/decrement does not impact the value of the expression,
so this increment/decrement has no effect.
Please verify that this statement does the right thing.
DLS: クラスリテラルã®ç„¡åŠ¹ãªä»£å…¥ (DLS_DEAD_STORE_OF_CLASS_LITERAL)¶
This instruction assigns a class literal to a variable and then never uses it.
The behavior of this differs in Java 1.4 and in Java 5.
In Java 1.4 and earlier, a reference to Foo.class
would force the static initializer
for Foo
to be executed, if it has not been executed already.
In Java 5 and later, it does not.
See Sun's article on Java SE compatibility for more details and examples, and suggestions on how to force class initialization in Java 5.
IP: メソッドã§èªã¿å–られãšã«ä¸Šæ›¸ãã•ã‚Œã¦ã„るパラメータ (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)¶
The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller.
MF: ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’éš ã™å¤‰æ•°ã‚’定義ã—ã¦ã„るメソッド (MF_METHOD_MASKS_FIELD)¶
This method defines a local variable with the same name as a field in this class or a superclass. This may cause the method to read an uninitialized value from the field, leave the field uninitialized, or both.
MF: スーパークラスã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’éš ã™ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã‚’定義ã—ã¦ã„るクラス (MF_CLASS_MASKS_FIELD)¶
This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.
FE: NaN ã¸ã®ç‰ä¾¡æ€§ã®ãŸã‚ã®çµ¶æœ›çš„ãªãƒ†ã‚¹ãƒˆ (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)¶
This code checks to see if a floating point value is equal to the special
Not A Number value (e.g., if (x == Double.NaN)
). However,
because of the special semantics of NaN
, no value
is equal to Nan
, including NaN
. Thus,
x == Double.NaN
always evaluates to false.
To check to see if a value contained in x
is the special Not A Number value, use
Double.isNaN(x)
(or Float.isNaN(x)
if
x
is floating point precision).
ICAST: int 値を long ã«å¤‰æ›ã—ã¦çµ¶å¯¾æ™‚é–“ã¨ã—ã¦ä½¿ç”¨ã—ã¦ã„ã‚‹ (ICAST_INT_2_LONG_AS_INSTANT)¶
This code converts a 32-bit int value to a 64-bit long value, and then passes that value for a method parameter that requires an absolute time value. An absolute time value is the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. For example, the following method, intended to convert seconds since the epoch into a Date, is badly broken:
Date getDate(int seconds) { return new Date(seconds * 1000); }
The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value. When a 32-bit value is converted to 64-bits and used to express an absolute time value, only dates in December 1969 and January 1970 can be represented.
Correct implementations for the above method are:
// Fails for dates after 2037
Date getDate(int seconds) { return new Date(seconds * 1000L); }
// better, works for all dates
Date getDate(long seconds) { return new Date(seconds * 1000); }
ICAST: 整数値を double ã«ã‚ャストã—㦠Math.ceil() ã«æ¸¡ã—ã¦ã„ã‚‹ (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)¶
This code converts an integral value (e.g., int or long) to a double precision floating point number and then passing the result to the Math.ceil() function, which rounds a double to the next higher integer value. This operation should always be a no-op, since the converting an integer to a double should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.ceil was intended to be performed using double precision floating point arithmetic.
ICAST: 整数値を float ã«ã‚ャストã—㦠Math.round() ã«æ¸¡ã—ã¦ã„ã‚‹ (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)¶
This code converts an int value to a float precision floating point number and then passing the result to the Math.round() function, which returns the int/long closest to the argument. This operation should always be a no-op, since the converting an integer to a float should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.round was intended to be performed using floating point arithmetic.
NP: null ã¨ã‚ã‹ã£ã¦ã„る値をãã®åž‹ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ãªã®ã‹ç¢ºã‹ã‚ã¦ã„ã‚‹ (NP_NULL_INSTANCEOF)¶
This instanceof test will always return false, since the value being checked is guaranteed to be null. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error.
NP: A known null value is checked to see if it is an instance of a type (BC_NULL_INSTANCEOF)¶
This instanceof test will always return false, since the value being checked is guaranteed to be null. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error.
DMI: int ã«å¯¾ã—㦠Double.longBitsToDouble() を呼ã³å‡ºã—ã¦ã„ã‚‹ (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)¶
The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed as an argument. This almost certainly is not intended and is unlikely to give the intended result.
BC: プリミティブ型ã®é…列をå«ã‚“ã§ã„ã‚‹ä¸å¯èƒ½ãªã‚ャスト (BC_IMPOSSIBLE_CAST_PRIMITIVE_ARRAY)¶
This cast will always throw a ClassCastException.
BC: ä¸å¯èƒ½ãªã‚ャスト (BC_IMPOSSIBLE_CAST)¶
This cast will always throw a ClassCastException. SpotBugs tracks type information from instanceof checks, and also uses more precise information about the types of values returned from methods and loaded from fields. Thus, it may have more precise information that just the declared type of a variable, and can use this to determine that a cast will always throw an exception at runtime.
BC: ä¸å¯èƒ½ãªãƒ€ã‚¦ãƒ³ã‚ャスト (BC_IMPOSSIBLE_DOWNCAST)¶
This cast will always throw a ClassCastException. The analysis believes it knows the precise type of the value being cast, and the attempt to downcast it to a subtype will always fail by throwing a ClassCastException.
BC: toArray メソッドã®çµæžœã®ä¸å¯èƒ½ãªãƒ€ã‚¦ãƒ³ã‚ャスト (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)¶
This code is casting the result of calling toArray()
on a collection
to a type more specific than Object[]
, as in:
String[] getAsArray(Collection<String> c) {
return (String[]) c.toArray();
}
This will usually fail by throwing a ClassCastException. The toArray()
of almost all collections return an Object[]
. They can't really do anything else,
since the Collection object has no reference to the declared generic type of the collection.
The correct way to do get an array of a specific type from a collection is to use
c.toArray(new String[]);
or c.toArray(new String[c.size()]);
(the latter is slightly more efficient).
There is one common/known exception to this. The toArray()
method of lists returned by Arrays.asList(...)
will return a covariantly
typed array. For example, Arrays.asArray(new String[] { "a" }).toArray()
will return a String []
. SpotBugs attempts to detect and suppress
such cases, but may miss some.
BC: 常㫠false を返㙠instanceof (BC_IMPOSSIBLE_INSTANCEOF)¶
This instanceof test will always return false. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error.
RE: æ£è¦è¡¨ç¾ã®ãŸã‚ã«ä½¿ã‚ã‚Œã¦ã„ã‚‹ ”.” ã¾ãŸã¯ “|” (RE_POSSIBLE_UNINTENDED_PATTERN)¶
A String function is being invoked and "." or "|" is being passed to a parameter that takes a regular expression as an argument. Is this what you intended? For example
- s.replaceAll(".", "/") will return a String in which every character has been replaced by a '/' character
- s.split(".") always returns a zero length array of String
- "ab|cd".replaceAll("|", "/") will return "/a/b/|/c/d/"
- "ab|cd".split("|") will return array with six (!) elements: [, a, b, |, c, d]
RE: æ£è¦è¡¨ç¾ã®ãŸã‚ã®ç„¡åŠ¹ãªæ§‹æ–‡ (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)¶
The code here uses a regular expression that is invalid according to the syntax for regular expressions. This statement will throw a PatternSyntaxException when executed.
RE: æ£è¦è¡¨ç¾ã®ãŸã‚ã«ä½¿ã‚ã‚Œã¦ã„ã‚‹ File.separator (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)¶
The code here uses File.separator
where a regular expression is required. This will fail on Windows
platforms, where the File.separator
is a backslash, which is interpreted in a
regular expression as an escape character. Among other options, you can just use
File.separatorChar=='\\' ? "\\\\" : File.separator
instead of
File.separator
DLS: 上書ãã•ã‚ŒãŸã‚¤ãƒ³ã‚¯ãƒªãƒ¡ãƒ³ãƒˆ (DLS_OVERWRITTEN_INCREMENT)¶
The code performs an increment operation (e.g., i++
) and then
immediately overwrites it. For example, i = i++
immediately
overwrites the incremented value with the original value.
BSHIFT: 32ビット int ã®-31ã‹ã‚‰31ã®ç¯„囲を超ãˆãŸé‡ã«ã‚ˆã‚‹ã‚·ãƒ•ãƒˆ (ICAST_BAD_SHIFT_AMOUNT)¶
The code performs shift of a 32 bit int by a constant amount outside the range -31..31. The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, and shifting by 32 bits is the same as shifting by zero bits). This probably isn't what was expected, and it is at least confusing.
BSHIFT: シフト演算ã®æ£ã—ããªã„構文解æžã®å¯èƒ½æ€§ãŒã‚ã‚‹ (BSHIFT_WRONG_ADD_PRIORITY)¶
The code performs an operation like (x << 8 + y). Although this might be correct, probably it was meant to perform (x << 8) + y, but shift operation has a lower precedence, so it's actually parsed as x << (8 + y).
IM: 整数剰余ã®çµæžœã®æ•´æ•°ä¹—ç®— (IM_MULTIPLYING_RESULT_OF_IREM)¶
The code multiplies the result of an integer remaining by an integer constant. Be sure you don't have your operator precedence confused. For example i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000).
DMI: é…列㧠hashCode メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (DMI_INVOKING_HASHCODE_ON_ARRAY)¶
The code invokes hashCode on an array. Calling hashCode on
an array returns the same value as System.identityHashCode, and ignores
the contents and length of the array. If you need a hashCode that
depends on the contents of an array a
,
use java.util.Arrays.hashCode(a)
.
USELESS_STRING: é…列㧠toString メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (DMI_INVOKING_TOSTRING_ON_ARRAY)¶
The code invokes toString on an array, which will generate a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12.
USELESS_STRING: åå‰ã®ãªã„é…列㧠toString メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)¶
The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12.
DMI: 月ã®ãŸã‚ã®é–“é•ã£ãŸå®šæ•°å€¤ (DMI_BAD_MONTH)¶
This code passes a constant month value outside the expected range of 0..11 to a method.
DMI: hasNext メソッド㧠next メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (DMI_CALLING_NEXT_FROM_HASNEXT)¶
The hasNext() method invokes the next() method. This is almost certainly wrong, since the hasNext() method is not supposed to change the state of the iterator, and the next method is supposed to change the state of the iterator.
QBA: è«–ç†å¼ã§ boolean リテラル値を代入ã—ã¦ã„るメソッド (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)¶
This method assigns a literal boolean value (true or false) to a boolean variable inside an if or while expression. Most probably this was supposed to be a boolean comparison using ==, not an assignment using =.
DMI: コレクションã¸ã®ç„¡æ„味ãªå‘¼ã³å‡ºã— (DMI_VACUOUS_SELF_COLLECTION_CALL)¶
This call doesn't make sense. For any collection c
, calling c.containsAll(c)
should
always be true, and c.retainAll(c)
should have no effect.
DMI: D’oh! ç„¡æ„味ãªãƒ¡ã‚½ãƒƒãƒ‰å‘¼ã³å‡ºã— (DMI_DOH)¶
This partical method invocation doesn't make sense, for reasons that should be apparent from inspection.
DMI: コレクションã¯è‡ªåˆ†è‡ªèº«ã‚’å«ã‚ã‚‹ã¹ãã§ã¯ãªã„ (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)¶
This call to a generic collection's method would only make sense if a collection contained
itself (e.g., if s.contains(s)
were true). This is unlikely to be true and would cause
problems if it were true (such as the computation of the hash code resulting in infinite recursion).
It is likely that the wrong value is being passed as a parameter.
TQ: 型修飾åãŒãªã„値ãŒä¿®é£¾åã‚’å¿…è¦ã¨ã™ã‚‹å ´æ‰€ã§ä½¿ã‚ã‚Œã¦ã„ã‚‹ (TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED)¶
A value is being used in a way that requires the value be annotation with a type qualifier. The type qualifier is strict, so the tool rejects any values that do not have the appropriate annotation.
To coerce a value to have a strict annotation, define an identity function where the return value is annotated with the strict annotation. This is the only way to turn a non-annotated value into a value with a strict type qualifier annotation.
TQ: 互æ›æ€§ã®ãªã„型修飾åã«ã‚ˆã‚‹æ¯”較値 (TQ_COMPARING_VALUES_WITH_INCOMPATIBLE_TYPE_QUALIFIERS)¶
A value specified as carrying a type qualifier annotation is compared with a value that doesn't ever carry that qualifier.
More precisely, a value annotated with a type qualifier specifying when=ALWAYS is compared with a value that where the same type qualifier specifies when=NEVER.
For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER). The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative.
public boolean example(@Negative Integer value1, @NonNegative Integer value2) {
return value1.equals(value2);
}
TQ: 型修飾åアノテーションãŒä»˜ã‘られãŸå€¤ãŒãã®ä¿®é£¾åを付ã‘ã¦ã¯ãªã‚‰ãªã„値を必è¦ã¨ã™ã‚‹å ´æ‰€ã§ä½¿ã‚ã‚Œã¦ã„ã‚‹ (TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED)¶
A value specified as carrying a type qualifier annotation is consumed in a location or locations requiring that the value not carry that annotation.
More precisely, a value annotated with a type qualifier specifying when=ALWAYS is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER.
For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER). The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative.
public @NonNegative Integer example(@Negative Integer value) {
return value;
}
TQ: 型修飾åアノテーションãŒä»˜ã‘られã¦ã„ãªã„値ãŒãã®ä¿®é£¾åãŒä»˜ã‘られãŸå€¤ã‚’å¿…è¦ã¨ã™ã‚‹å ´æ‰€ã§ä½¿ã‚ã‚Œã¦ã„ã‚‹ (TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED)¶
A value specified as not carrying a type qualifier annotation is guaranteed to be consumed in a location or locations requiring that the value does carry that annotation.
More precisely, a value annotated with a type qualifier specifying when=NEVER is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS.
TODO: example
TQ: 型修飾åを付ã‘ã¦ã„ãªã„ã‹ã‚‚ã—ã‚Œãªã„値ãŒãã®åž‹ä¿®é£¾åã‚’å¿…è¦ã¨ã™ã‚‹æ–¹æ³•ã§å¸¸ã«ä½¿ã‚ã‚Œã¦ã„ã‚‹ (TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK)¶
A value that is annotated as possibility not being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that requires values denoted by that type qualifier.
TQ: 型修飾åを付ã‘ã¦ã„ã‚‹ã‹ã‚‚ã—ã‚Œãªã„値ãŒãã®åž‹ä¿®é£¾åã‚’ç¦æ¢ã™ã‚‹æ–¹æ³•ã§å¸¸ã«ä½¿ã‚ã‚Œã¦ã„ã‚‹ (TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK)¶
A value that is annotated as possibility being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that prohibits values denoted by that type qualifier.
FB: FindBugs ã‹ã‚‰ã®äºˆæœŸã—ãªã„/望ã¾ã—ããªã„è¦å‘Š (FB_UNEXPECTED_WARNING)¶
SpotBugs generated a warning that, according to a @NoWarning annotated, is unexpected or undesired.
FB: 失ã‚れ㟠FindBugs ã‹ã‚‰ã®äºˆæœŸã—ãŸ/望ã¾ã—ã„è¦å‘Š (FB_MISSING_EXPECTED_WARNING)¶
SpotBugs didn't generate generated a warning that, according to a @ExpectedWarning annotated, is expected or desired.
実験用 (EXPERIMENTAL)¶
Experimental and not fully vetted bug patterns
SKIPPED: 解æžã™ã‚‹ã«ã¯ã‚ã¾ã‚Šã«ã‚‚大ãã„クラス (SKIPPED_CLASS_TOO_BIG)¶
This class is bigger than can be effectively handled, and was not fully analyzed for errors.
TEST: 未知ã®ãƒã‚°ãƒ‘ターン (UNKNOWN)¶
A warning was recorded, but SpotBugs can't find the description of this bug pattern and so can't describe it. This should occur only in cases of a bug in SpotBugs or its configuration, or perhaps if an analysis was generated using a plugin, but that plugin is not currently loaded. .
TEST: テスト (TESTING)¶
This bug pattern is only generated by new, incompletely implemented bug detectors.
TEST: テスト1 (TESTING1)¶
This bug pattern is only generated by new, incompletely implemented bug detectors.
TEST: テスト2 (TESTING2)¶
This bug pattern is only generated by new, incompletely implemented bug detectors.
TEST: テスト3 (TESTING3)¶
This bug pattern is only generated by new, incompletely implemented bug detectors.
OBL: ストリームやリソースã®ã‚¯ãƒªãƒ¼ãƒ³ã‚¢ãƒƒãƒ—ã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (OBL_UNSATISFIED_OBLIGATION)¶
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.
In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.
This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback:
- file an issue: https://github.com/spotbugs/spotbugs/issues
In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us.
See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique.
OBL: ãƒã‚§ãƒƒã‚¯ä¾‹å¤–ã§ã‚¹ãƒˆãƒªãƒ¼ãƒ やリソースã®ã‚¯ãƒªãƒ¼ãƒ³ã‚¢ãƒƒãƒ—ã«å¤±æ•—ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE)¶
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.
In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.
This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback, either:
- send email to findbugs@cs.umd.edu
- file a bug report: http://findbugs.sourceforge.net/reportingBugs.html
In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us.
See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique.
LG: ãƒã‚¬ãƒ¼ã®å¤‰æ›´ã¯ OpenJDK ã®å¼±å‚ç…§ãŒåŽŸå› ã§æ½œåœ¨çš„ã«å¤±ã‚れる (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)¶
OpenJDK introduces a potential incompatibility. In particular, the java.util.logging.Logger behavior has changed. Instead of using strong references, it now uses weak references internally. That's a reasonable change, but unfortunately some code relies on the old behavior - when changing logger configuration, it simply drops the logger reference. That means that the garbage collector is free to reclaim that memory, which means that the logger configuration is lost. For example, consider:
public static void initLogging() throws Exception {
Logger logger = Logger.getLogger("edu.umd.cs");
logger.addHandler(new FileHandler()); // call to change logger configuration
logger.setUseParentHandlers(false); // another call to change logger configuration
}
The logger reference is lost at the end of the method (it doesn't escape the method), so if you have a garbage collection cycle just after the call to initLogging, the logger configuration is lost (because Logger only keeps weak references).
public static void main(String[] args) throws Exception {
initLogging(); // adds a file handler to the logger
System.gc(); // logger configuration lost
Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
}
Ulf Ochsenfahrt and Eric Fellheimer
国際化 (I18N)¶
code flaws having to do with internationalization and locale
Dm: 呼ã³å‡ºã—ãŸãƒ¡ã‚½ãƒƒãƒ‰ã® Locale パラメータã®ä½¿ç”¨ã‚’検討ã™ã‚‹ (DM_CONVERT_CASE)¶
A String is being converted to upper or lowercase, using the platform's default encoding. This may result in improper conversions when used with international characters. Use the
- String.toUpperCase( Locale l )
- String.toLowerCase( Locale l )
versions instead.
Dm: デフォルトエンコーディングã¸ã®ä¾å˜ (DM_DEFAULT_ENCODING)¶
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.
悪æ„ã®ã‚るコード脆弱性 (MALICIOUS_CODE)¶
code that is vulnerable to attacks from untrusted code
DP: doPrivileged ブãƒãƒƒã‚¯å†…ã§å‘¼ã³å‡ºã™ã¹ãメソッド (DP_DO_INSIDE_DO_PRIVILEGED)¶
This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block.
DP: doPrivileged ブãƒãƒƒã‚¯å†…ã§ä½œæˆã•ã‚Œã‚‹ã¹ãクラスãƒãƒ¼ãƒ€ (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)¶
This code creates a classloader, which needs permission if a security manage is installed. If this code might be invoked by code that does not have security permissions, then the classloader creation needs to occur inside a doPrivileged block.
FI: ファイナライザ㯠public ã§ã¯ãªã protected ã«ã™ã¹ã (FI_PUBLIC_SHOULD_BE_PROTECTED)¶
A class's finalize()
method should have protected access,
not public.
MS: é…列を返ã™ã“ã¨ã«ã‚ˆã£ã¦å†…部表ç¾ã‚’暴露ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„ public static メソッド (MS_EXPOSE_REP)¶
A public static method returns a reference to an array that is part of the static state of the class. Any code that calls this method can freely modify the underlying array. One fix is to return a copy of the array.
EI: å¯å¤‰ã‚ªãƒ–ジェクトã¸ã®å‚照を返ã™ã“ã¨ã«ã‚ˆã£ã¦å†…部表ç¾ã‚’暴露ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (EI_EXPOSE_REP)¶
Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations.
EI2: å¯å¤‰ã‚ªãƒ–ジェクトã¸ã®å‚照をå–り込むã“ã¨ã«ã‚ˆã£ã¦å†…部表ç¾ã‚’暴露ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (EI_EXPOSE_REP2)¶
This code stores a reference to an externally mutable object into the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.
MS: static フィールドã«å¯å¤‰ã‚ªãƒ–ã‚¸ã‚§ã‚¯ãƒˆã‚’æ ¼ç´ã™ã‚‹ã“ã¨ã«ã‚ˆã£ã¦ï¼Œå†…部ã®é™çš„状態を暴露ã™ã‚‹ã‹ã‚‚ã—ã‚Œãªã„メソッド (EI_EXPOSE_STATIC_REP2)¶
This code stores a reference to an externally mutable object into a static field. If unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.
MS: インタフェースã‹ã‚‰ç§»å‹•ã—ã¦ãƒ‘ッケージプãƒãƒ†ã‚¯ãƒ†ãƒƒãƒ‰ã«ã™ã¹ãフィールド (MS_OOI_PKGPROTECT)¶
A final static field that is defined in an interface references a mutable object such as an array or hashtable. This mutable object could be changed by malicious code or by accident from another package. To solve this, the field needs to be moved to a class and made package protected to avoid this vulnerability.
MS: final ã‹ã¤ãƒ‘ッケージプãƒãƒ†ã‚¯ãƒ†ãƒƒãƒ‰ã«ã™ã¹ãフィールド (MS_FINAL_PKGPROTECT)¶
A mutable static field could be changed by malicious code or by accident from another package. The field could be made package protected and/or made final to avoid this vulnerability.
MS: final ã«ã™ã¹ãフィールド (MS_SHOULD_BE_FINAL)¶
This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability.
MS: final ã§ã¯ãªã„フィールドã¯ãƒªãƒ•ã‚¡ã‚¯ã‚¿ãƒªãƒ³ã‚°ã™ã¹ã (MS_SHOULD_BE_REFACTORED_TO_BE_FINAL)¶
This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability. However, the static initializer contains more than one write to the field, so doing so will require some refactoring.
MS: パッケージプãƒãƒ†ã‚¯ãƒ†ãƒƒãƒ‰ã«ã™ã¹ãフィールド (MS_PKGPROTECT)¶
A mutable static field could be changed by malicious code or by accident. The field could be made package protected to avoid this vulnerability.
MS: å¯å¤‰ Hashtable ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (MS_MUTABLE_HASHTABLE)¶
A final static field references a Hashtable and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the Hashtable.
MS: å¯å¤‰é…列ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (MS_MUTABLE_ARRAY)¶
A final static field references an array and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the array.
MS: å¯å¤‰ã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (MS_MUTABLE_COLLECTION)¶
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
MS: パッケージプãƒãƒ†ã‚¯ãƒ†ãƒƒãƒ‰ã«ã™ã¹ãå¯å¤‰ã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (MS_MUTABLE_COLLECTION_PKGPROTECT)¶
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. The field could be made package protected to avoid this vulnerability. Alternatively you may wrap this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
MS: final ã§ã¯ãªã„フィールドã¯æ‚ªæ„ã®ã‚るコードã‹ã‚‰ä¿è·ã§ããªã„ (MS_CANNOT_BE_FINAL)¶
A mutable static field could be changed by malicious code or by accident from another package. Unfortunately, the way the field is used doesn't allow any easy fix to this problem.
マルãƒã‚¹ãƒ¬ãƒƒãƒ‰ã®æ£ç¢ºæ€§ (MT_CORRECTNESS)¶
code flaws having to do with threads, locks, and volatiles
AT: 並行抽象ã®å‘¼ã³å‡ºã—シーケンスã¯ã‚¢ãƒˆãƒŸãƒƒã‚¯ã§ã¯ãªã„ã‹ã‚‚ã—ã‚Œãªã„ (AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION)¶
This code contains a sequence of calls to a concurrent abstraction (such as a concurrent hash map). These calls will not be executed atomically.
STCAL: static Calendar フィールド (STCAL_STATIC_CALENDAR_INSTANCE)¶
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate().
You may also experience serialization problems.
Using an instance field is recommended.
For more information on this see JDK Bug #6231579 and JDK Bug #6178997.
STCAL: static DateFormat フィールド (STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)¶
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.
You may also experience serialization problems.
Using an instance field is recommended.
For more information on this see JDK Bug #6231579 and JDK Bug #6178997.
STCAL: static Calendar ã®å‘¼ã³å‡ºã— (STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)¶
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multithreaded use. The detector has found a call to an instance of Calendar that has been obtained via a static field. This looks suspicious.
For more information on this see JDK Bug #6231579 and JDK Bug #6178997.
STCAL: static DateFormat ã®å‘¼ã³å‡ºã— (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)¶
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. This looks suspicious.
For more information on this see JDK Bug #6231579 and JDK Bug #6178997.
NP: åŒã˜ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã§ã®åŒæœŸåŒ–㨠null ãƒã‚§ãƒƒã‚¯ (NP_SYNC_AND_NULL_CHECK_FIELD)¶
Since the field is synchronized on, it seems not likely to be null. If it is null and then synchronized on a NullPointerException will be thrown and the check would be pointless. Better to synchronize on another field.
VO: é…列ã¸ã® volatile å‚ç…§ã¯ï¼Œé…列è¦ç´ ã‚’ volatile ã¨ã—ã¦æ‰±ã‚ãªã„ (VO_VOLATILE_REFERENCE_TO_ARRAY)¶
This declares a volatile reference to an array, which might not be what you want. With a volatile reference to an array, reads and writes of the reference to the array are treated as volatile, but the array elements are non-volatile. To get volatile array elements, you will need to use one of the atomic array classes in java.util.concurrent (provided in Java 5.0).
VO: volatile フィールドã¸ã®ã‚¤ãƒ³ã‚¯ãƒªãƒ¡ãƒ³ãƒˆã¯ã‚¢ãƒˆãƒŸãƒƒã‚¯ã§ã¯ãªã„ (VO_VOLATILE_INCREMENT)¶
This code increments a volatile field. Increments of volatile fields aren't atomic. If more than one thread is incrementing the field at the same time, increments could be lost.
Dm: Condition ã§å‘¼ã³å‡ºã•ã‚ŒãŸ wait メソッドを監視ã—ã¦ã„ã‚‹ (DM_MONITOR_WAIT_ON_CONDITION)¶
This method calls wait()
on a
java.util.concurrent.locks.Condition
object.
Waiting for a Condition
should be done using one of the await()
methods defined by the Condition
interface.
Dm: デフォルトã®ç©ºã® run メソッドを使用ã—ã¦ä½œæˆã•ã‚ŒãŸã‚¹ãƒ¬ãƒƒãƒ‰ (DM_USELESS_THREAD)¶
This method creates a thread without specifying a run method either by deriving from the Thread class, or by passing a Runnable object. This thread, then, does nothing but waste time.
DC: フィールドã®ãƒ€ãƒ–ルãƒã‚§ãƒƒã‚¯ã®å¯èƒ½æ€§ (DC_DOUBLECHECK)¶
This method may contain an instance of double-checked locking. This idiom is not correct according to the semantics of the Java memory model. For more information, see the web page http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.
DC: 部分的ã«åˆæœŸåŒ–ã•ã‚ŒãŸã‚ªãƒ–ジェクトを暴露ã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚‹ (DC_PARTIALLY_CONSTRUCTED)¶
Looks like this method uses lazy field initialization with double-checked locking. While the field is correctly declared as volatile, it's possible that the internal structure of the object is changed after the field assignment, thus another thread may see the partially initialized object.
To fix this problem consider storing the object into the local variable first and save it to the volatile field only after it's fully constructed.
DL: Boolean ã®åŒæœŸåŒ– (DL_SYNCHRONIZATION_ON_BOOLEAN)¶
The code synchronizes on a boxed primitive constant, such as a Boolean.
private static Boolean inited = Boolean.FALSE;
...
synchronized(inited) {
if (!inited) {
init();
inited = Boolean.TRUE;
}
}
...
Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock.
See CERT CON08-J. Do not synchronize on objects that may be reused for more information.
DL: ボクシングã•ã‚ŒãŸãƒ—リミティブã®åŒæœŸåŒ– (DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE)¶
The code synchronizes on a boxed primitive constant, such as an Integer.
private static Integer count = 0;
...
synchronized(count) {
count++;
}
...
Since Integer objects can be cached and shared, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock.
See CERT CON08-J. Do not synchronize on objects that may be reused for more information.
WL: クラスリテラルã§ã¯ãªã getClass ã§åŒæœŸåŒ–ã—ã¦ã„ã‚‹ (WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)¶
This instance method synchronizes on this.getClass()
. If this class is subclassed,
subclasses will synchronize on the class object for the subclass, which isn't likely what was intended.
For example, consider this code from java.awt.Label:
private static final String base = "label";
private static int nameCounter = 0;
String constructComponentName() {
synchronized (getClass()) {
return base + nameCounter++;
}
}
Subclasses of Label
won't synchronize on the same subclass, giving rise to a datarace.
Instead, this code should be synchronizing on Label.class
private static final String base = "label";
private static int nameCounter = 0;
String constructComponentName() {
synchronized (Label.class) {
return base + nameCounter++;
}
}
Bug pattern contributed by Jason Mehrens
ESync: 空㮠synchronized ブãƒãƒƒã‚¯ (ESync_EMPTY_SYNC)¶
The code contains an empty synchronized block:
synchronized() {
}
Empty synchronized blocks are far more subtle and hard to use correctly than most people recognize, and empty synchronized blocks are almost never a better solution than less contrived solutions.
MSF: å¯å¤‰ã‚µãƒ¼ãƒ–レットフィールド (MSF_MUTABLE_SERVLET_FIELD)¶
A web server generally only creates one instance of servlet or JSP class (i.e., treats the class as a Singleton), and will have multiple threads invoke methods on that instance to service multiple simultaneous requests. Thus, having a mutable instance field generally creates race conditions.
IS: 一貫性ã®ãªã„åŒæœŸåŒ– (IS2_INCONSISTENT_SYNC)¶
The fields of this class appear to be accessed inconsistently with respect to synchronization. This bug report indicates that the bug pattern detector judged that
- The class contains a mix of locked and unlocked accesses,
- The class is not annotated as javax.annotation.concurrent.NotThreadSafe,
- At least one locked access was performed by one of the class's own methods, and
- The number of unsynchronized field accesses (reads and writes) was no more than one third of all accesses, with writes being weighed twice as high as reads
A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.
You can select the nodes labeled "Unsynchronized access" to show the code locations where the detector believed that a field was accessed without synchronization.
Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.
NN: 裸㮠notify メソッド (NN_NAKED_NOTIFY)¶
A call to notify()
or notifyAll()
was made without any (apparent) accompanying
modification to mutable object state. In general, calling a notify
method on a monitor is done because some condition another thread is
waiting for has become true. However, for the condition to be meaningful,
it must involve a heap object that is visible to both threads.
This bug does not necessarily indicate an error, since the change to mutable object state may have taken place in a method which then called the method containing the notification.
Ru: スレッド㧠run メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (RU_INVOKE_RUN)¶
This method explicitly invokes run()
on an object.
In general, classes implement the Runnable
interface because
they are going to have their run()
method invoked in a new thread,
in which case Thread.start()
is the right method to call.
SP: スピンãƒãƒƒã‚¯ã‚’ã—ã¦ã„るメソッド (SP_SPIN_ON_FIELD)¶
This method spins in a loop which reads a field. The compiler may legally hoist the read out of the loop, turning the code into an infinite loop. The class should be changed so it uses proper synchronization (including wait and notify calls).
TLW: 2ã¤ä»¥ä¸Šã®ãƒãƒƒã‚¯ã‚’ä¿æŒã—㦠wait メソッドを呼ã³å‡ºã—ã¦ã„ã‚‹ (TLW_TWO_LOCK_WAIT)¶
Waiting on a monitor while two locks are held may cause deadlock. Performing a wait only releases the lock on the object being waited on, not any other locks. This not necessarily a bug, but is worth examining closely.
TLW: Notify with two locks held (TLW_TWO_LOCK_NOTIFY)¶
The code calls notify() or notifyAll() while two locks are held. If this notification is intended to wake up a wait() that is holding the same locks, it may deadlock, since the wait will only give up one lock and the notify will be unable to get both locks, and thus the notify will not succeed. If there is also a warning about a two lock wait, the probably of a bug is quite high.
UW: wait メソッドã®ç„¡æ¡ä»¶å‘¼ã³å‡ºã— (UW_UNCOND_WAIT)¶
This method contains a call to java.lang.Object.wait()
which
is not guarded by conditional control flow. The code should
verify that condition it intends to wait for is not already satisfied
before calling wait; any previous notifications will be ignored.
UG: åŒæœŸåŒ–ã—ã¦ã„ãªã„ get メソッド,åŒæœŸåŒ–ã—ã¦ã„ã‚‹ set メソッド (UG_SYNC_SET_UNSYNC_GET)¶
This class contains similarly-named get and set methods where the set method is synchronized and the get method is not. This may result in incorrect behavior at runtime, as callers of the get method will not necessarily see a consistent state for the object. The get method should be made synchronized.
IS: 一貫性ã®ãªã„åŒæœŸåŒ– (IS_INCONSISTENT_SYNC)¶
The fields of this class appear to be accessed inconsistently with respect to synchronization. This bug report indicates that the bug pattern detector judged that
- The class contains a mix of locked and unlocked accesses,
- At least one locked access was performed by one of the class's own methods, and
- The number of unsynchronized field accesses (reads and writes) was no more than one third of all accesses, with writes being weighed twice as high as reads
A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.
Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.
IS: 並行アクセスã«å¯¾ã—ã¦ã‚¬ãƒ¼ãƒ‰ã•ã‚Œã¦ã„ãªã„フィールド (IS_FIELD_NOT_GUARDED)¶
This field is annotated with net.jcip.annotations.GuardedBy or javax.annotation.concurrent.GuardedBy, but can be accessed in a way that seems to violate those annotations.
ML: フィールドをåŒæœŸåŒ–ã§ã‚¬ãƒ¼ãƒ‰ã—よã†ã¨ã™ã‚‹ç„¡é§„ãªè©¦ã¿ (ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD)¶
This method synchronizes on a field in what appears to be an attempt to guard against simultaneous updates to that field. But guarding a field gets a lock on the referenced object, not on the field. This may not provide the mutual exclusion you need, and other threads might be obtaining locks on the referenced objects (for other purposes). An example of this pattern would be:
private Long myNtfSeqNbrCounter = new Long(0);
private Long getNotificationSequenceNumber() {
Long result = null;
synchronized(myNtfSeqNbrCounter) {
result = new Long(myNtfSeqNbrCounter.longValue() + 1);
myNtfSeqNbrCounter = new Long(result.longValue());
}
return result;
}
ML: æ›´æ–°ã•ã‚Œã‚‹ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ã§åŒæœŸåŒ–ã—ã¦ã„るメソッド (ML_SYNC_ON_UPDATED_FIELD)¶
This method synchronizes on an object referenced from a mutable field. This is unlikely to have useful semantics, since different threads may be synchronizing on different objects.
WS: writeObject メソッドã¯åŒæœŸåŒ–ã—ã¦ã„ã‚‹ãŒãã®ä»–ã®ãƒ¡ã‚½ãƒƒãƒ‰ã¯åŒæœŸåŒ–ã—ã¦ã„ãªã„クラス (WS_WRITEOBJECT_SYNC)¶
This class has a writeObject()
method which is synchronized;
however, no other method of the class is synchronized.
RS: readObject メソッドをåŒæœŸåŒ–ã—ã¦ã„るクラス (RS_READOBJECT_SYNC)¶
This serializable class defines a readObject()
which is
synchronized. By definition, an object created by deserialization
is only reachable by one thread, and thus there is no need for
readObject()
to be synchronized. If the readObject()
method itself is causing the object to become visible to another thread,
that is an example of very dubious coding style.
SC: Thread.start() を呼ã³å‡ºã—ã¦ã„るコンストラクタ (SC_START_IN_CTOR)¶
The constructor starts a thread. This is likely to be wrong if the class is ever extended/subclassed, since the thread will be started before the subclass constructor is started.
Wa: wait メソッドãŒãƒ«ãƒ¼ãƒ—ã®ä¸ã«ãªã„ (WA_NOT_IN_LOOP)¶
This method contains a call to java.lang.Object.wait()
which is not in a loop. If the monitor is used for multiple conditions,
the condition the caller intended to wait for might not be the one
that actually occurred.
Wa: Condition.await() ãŒãƒ«ãƒ¼ãƒ—ã®ä¸ã«ãªã„ (WA_AWAIT_NOT_IN_LOOP)¶
This method contains a call to java.util.concurrent.await()
(or variants)
which is not in a loop. If the object is used for multiple conditions,
the condition the caller intended to wait for might not be the one
that actually occurred.
No: notifyAll メソッドã§ã¯ãªã notify メソッドを使用ã—ã¦ã„ã‚‹ (NO_NOTIFY_NOT_NOTIFYALL)¶
This method calls notify()
rather than notifyAll()
.
Java monitors are often used for multiple conditions. Calling notify()
only wakes up one thread, meaning that the thread woken up might not be the
one waiting for the condition that the caller just satisfied.
UL: ã™ã¹ã¦ã®çµŒè·¯ã§ãƒãƒƒã‚¯ãŒè§£é™¤ã•ã‚Œãªã„メソッド (UL_UNRELEASED_LOCK)¶
This method acquires a JSR-166 (java.util.concurrent
) lock,
but does not release it on all paths out of the method. In general, the correct idiom
for using a JSR-166 lock is:
Lock l = ...;
l.lock();
try {
// do something
} finally {
l.unlock();
}
UL: ã™ã¹ã¦ã®ä¾‹å¤–経路ã§ãƒãƒƒã‚¯ãŒè§£é™¤ã•ã‚Œãªã„メソッド (UL_UNRELEASED_LOCK_EXCEPTION_PATH)¶
This method acquires a JSR-166 (java.util.concurrent
) lock,
but does not release it on all exception paths out of the method. In general, the correct idiom
for using a JSR-166 lock is:
Lock l = ...;
l.lock();
try {
// do something
} finally {
l.unlock();
}
MWN: ä¸æ•´åˆãª wait メソッド (MWN_MISMATCHED_WAIT)¶
This method calls Object.wait() without obviously holding a lock
on the object. Calling wait() without a lock held will result in
an IllegalMonitorStateException
being thrown.
MWN: ä¸æ•´åˆãª notify メソッド (MWN_MISMATCHED_NOTIFY)¶
This method calls Object.notify() or Object.notifyAll() without obviously holding a lock
on the object. Calling notify() or notifyAll() without a lock held will result in
an IllegalMonitorStateException
being thrown.
LI: Incorrect lazy initialization of instance field (LI_LAZY_INIT_INSTANCE)¶
This method contains an unsynchronized lazy initialization of a non-volatile field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site.
LI: static フィールドã®é–“é•ã£ãŸé…延åˆæœŸåŒ– (LI_LAZY_INIT_STATIC)¶
This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site.
LI: æ›´æ–°ã•ã‚Œã‚‹ static フィールドã®é–“é•ã£ãŸé…延åˆæœŸåŒ– (LI_LAZY_INIT_UPDATE_STATIC)¶
This method contains an unsynchronized lazy initialization of a static field. After the field is set, the object stored into that location is further updated or accessed. The setting of the field is visible to other threads as soon as it is set. If the further accesses in the method that set the field serve to initialize the object, then you have a very serious multithreading bug, unless something else prevents any other thread from accessing the stored object until it is fully initialized.
Even if you feel confident that the method is never called by multiple threads, it might be better to not set the static field until the value you are setting it to is fully populated/initialized.
JLM: java.util.concurrent ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§åŒæœŸåŒ–ã—ã¦ã„ã‚‹ (JLM_JSR166_UTILCONCURRENT_MONITORENTER)¶
This method performs synchronization an object that is an instance of
a class from the java.util.concurrent package (or its subclasses). Instances
of these classes have their own concurrency control mechanisms that are orthogonal to
the synchronization provided by the Java keyword synchronized
. For example,
synchronizing on an AtomicBoolean
will not prevent other threads
from modifying the AtomicBoolean
.
Such code may be correct, but should be carefully reviewed and documented, and may confuse people who have to maintain the code at a later date.
JLM: util.concurrent 抽象化ã§ãƒ¢ãƒ‹ã‚¿ã‚¹ã‚¿ã‚¤ãƒ«ã® wait メソッドを使用ã—ã¦ã„ã‚‹ (JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT)¶
This method calls
wait()
,
notify()
or
notifyAll()()
on an object that also provides an
await()
,
signal()
,
signalAll()
method (such as util.concurrent Condition objects).
This probably isn't what you want, and even if you do want it, you should consider changing
your design, as other developers will find it exceptionally confusing.
JLM: Lock ã§åŒæœŸåŒ–ã—ã¦ã„ã‚‹ (JLM_JSR166_LOCK_MONITORENTER)¶
This method performs synchronization an object that implements
java.util.concurrent.locks.Lock. Such an object is locked/unlocked
using
acquire()
/release()
rather
than using the synchronized (...)
construct.
SWL: ãƒãƒƒã‚¯ã‚’ä¿æŒã—㦠Thread.sleep() を呼ã³å‡ºã—ã¦ã„るメソッド (SWL_SLEEP_WITH_LOCK_HELD)¶
This method calls Thread.sleep() with a lock held. This may result in very poor performance and scalability, or a deadlock, since other threads may be waiting to acquire the lock. It is a much better idea to call wait() on the lock, which releases the lock and allows other threads to run.
RV: putIfAbsent ã®æˆ»ã‚Šå€¤ã¯ç„¡è¦–ã•ã‚Œã¦ putIfAbsent ã«æ¸¡ã—ãŸå€¤ã¯å†åˆ©ç”¨ã•ã‚ŒãŸ (RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED)¶
TheputIfAbsent
method is typically used to ensure that a
single value is associated with a given key (the first value for which put
if absent succeeds).
If you ignore the return value and retain a reference to the value passed in,
you run the risk of retaining a value that is not the one that is associated with the key in the map.
If it matters which one you use and you use the one that isn't stored in the map,
your program will behave incorrectly.å½ã®ãƒ©ãƒ³ãƒ€ãƒ ノイズ (NOISE)¶
Bogus random noise: intended to be useful as a control in data mining experiments, not in finding actual bugs in software
NOISE: null ãƒã‚¤ãƒ³ã‚¿é–“接å‚ç…§ã«é–¢ã™ã‚‹å½ã®è¦å‘Š (NOISE_NULL_DEREFERENCE)¶
Bogus warning.
NOISE: メソッド呼ã³å‡ºã—ã«é–¢ã™ã‚‹å½ã®è¦å‘Š (NOISE_METHOD_CALL)¶
Bogus warning.
NOISE: フィールドå‚ç…§ã«é–¢ã™ã‚‹å½ã®è¦å‘Š (NOISE_FIELD_REFERENCE)¶
Bogus warning.
NOISE: 演算ã«é–¢ã™ã‚‹å½ã®è¦å‘Š (NOISE_OPERATION)¶
Bogus warning.
性能 (PERFORMANCE)¶
code that is not necessarily incorrect but may be inefficient
Dm: URL ã® equals メソッド㨠hashCode メソッドã¯ãƒ–ãƒãƒƒã‚¯ã™ã‚‹ (DMI_BLOCKING_METHODS_ON_URL)¶
The equals and hashCode
method of URL perform domain name resolution, this can result in a big performance hit.
See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
Consider using java.net.URI
instead.
Dm: URL ã® Map ã‚„ Set ã¯ã²ã©ã„性能ã«ãªã‚‹ (DMI_COLLECTION_OF_URLS)¶
This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode
method of URL perform domain name resolution, this can result in a big performance hit.
See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
Consider using java.net.URI
instead.
Dm: 効率ãŒæ‚ªã„ new String(String) コンストラクタを呼ã³å‡ºã—ã¦ã„るメソッド (DM_STRING_CTOR)¶
Using the java.lang.String(String)
constructor wastes memory
because the object so constructed will be functionally indistinguishable
from the String
passed as a parameter. Just use the
argument String
directly.
Dm: 効率ãŒæ‚ªã„ new String() コンストラクタを呼ã³å‡ºã—ã¦ã„るメソッド (DM_STRING_VOID_CTOR)¶
Creating a new java.lang.String
object using the
no-argument constructor wastes memory because the object so created will
be functionally indistinguishable from the empty string constant
""
. Java guarantees that identical string constants
will be represented by the same String
object. Therefore,
you should just use the empty string constant directly.
Dm: String ã® toString メソッドを呼ã³å‡ºã—ã¦ã„るメソッド (DM_STRING_TOSTRING)¶
Calling String.toString()
is just a redundant operation.
Just use the String.
Dm: 明示的ãªã‚¬ãƒ™ãƒ¼ã‚¸ã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ (DM_GC)¶
Code explicitly invokes garbage collection. Except for specific use in benchmarking, this is very dubious.
In the past, situations where people have explicitly invoked the garbage collector in routines such as close or finalize methods has led to huge performance black holes. Garbage collection can be expensive. Any situation that forces hundreds or thousands of garbage collections will bring the machine to a crawl.
Dm: 効率ãŒæ‚ªã„ Boolean コンストラクタを呼ã³å‡ºã—ã¦ã„るメソッド (DM_BOOLEAN_CTOR)¶
Creating new instances of java.lang.Boolean
wastes
memory, since Boolean
objects are immutable and there are
only two useful values of this type. Use the Boolean.valueOf()
method (or Java 1.5 autoboxing) to create Boolean
objects instead.
Bx: 効率ãŒæ‚ªã„ Number コンストラクタを呼ã³å‡ºã—ã¦ã„るメソッド (DM_NUMBER_CTOR)¶
Using new Integer(int)
is guaranteed to always result in a new object whereas
Integer.valueOf(int)
allows caching of values to be done by the compiler, class library, or JVM.
Using of cached values avoids object allocation and the code will be faster.
Values between -128 and 127 are guaranteed to have corresponding cached instances
and using valueOf
is approximately 3.5 times faster than using constructor.
For values outside the constant range the performance of both styles is the same.
Unless the class must be compatible with JVMs predating Java 1.5,
use either autoboxing or the valueOf()
method when creating instances of
Long
, Integer
, Short
, Character
, and Byte
.
Bx: 効率ãŒæ‚ªã„浮動å°æ•°ç‚¹ Number コンストラクタを呼ã³å‡ºã—ã¦ã„るメソッド (DM_FP_NUMBER_CTOR)¶
Using new Double(double)
is guaranteed to always result in a new object whereas
Double.valueOf(double)
allows caching of values to be done by the compiler, class library, or JVM.
Using of cached values avoids object allocation and the code will be faster.
Unless the class must be compatible with JVMs predating Java 1.5,
use either autoboxing or the valueOf()
method when creating instances of Double
and Float
.
Bx: toString メソッドを呼ã³å‡ºã™ãŸã‚ã ã‘ã«ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚ŒãŸãƒ—リミティブを割り当ã¦ã¦ã„ã‚‹ (DM_BOXED_PRIMITIVE_TOSTRING)¶
A boxed primitive is allocated just to call toString(). It is more effective to just use the static form of toString which takes the primitive value. So,
Replace... | With this... |
---|---|
new Integer(1).toString() | Integer.toString(1) |
new Long(1).toString() | Long.toString(1) |
new Float(1.0).toString() | Float.toString(1.0) |
new Double(1.0).toString() | Double.toString(1.0) |
new Byte(1).toString() | Byte.toString(1) |
new Short(1).toString() | Short.toString(1) |
new Boolean(true).toString() | Boolean.toString(true) |
Bx: プリミティブを解æžã™ã‚‹ãŸã‚ã®ãƒœã‚¯ã‚·ãƒ³ã‚°/アンボクシング (DM_BOXED_PRIMITIVE_FOR_PARSING)¶
A boxed primitive is created from a String, just to extract the unboxed primitive value. It is more efficient to just call the static parseXXX method.
Bx: プリミティブãŒæ¯”較ã§ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã¦ã„ã‚‹ (DM_BOXED_PRIMITIVE_FOR_COMPARE)¶
A boxed primitive is created just to call compareTo method. It's more efficient to use static compare method (for double and float since Java 1.4, for other primitive types since Java 1.7) which works on primitives directly.
Bx: プリミティブ値ãŒ3é …æ¼”ç®—åã®ãŸã‚ã«ã‚¢ãƒ³ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã¦ï¼Œåž‹å¤‰æ›ã•ã‚Œã‚‹ (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)¶
A wrapped primitive value is unboxed and converted to another primitive type as part of the
evaluation of a conditional ternary operator (the b ? e1 : e2
operator). The
semantics of Java mandate that if e1
and e2
are wrapped
numeric values, the values are unboxed and converted/coerced to their common type (e.g,
if e1
is of type Integer
and e2
is of type Float
, then e1
is unboxed,
converted to a floating point value, and boxed. See JLS Section 15.25.
Bx: ボクシングã•ã‚ŒãŸå€¤ãŒã‚¢ãƒ³ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã¦ï¼Œã™ãã«å†ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã‚‹ (BX_UNBOXING_IMMEDIATELY_REBOXED)¶
A boxed value is unboxed and then immediately reboxed.
Bx: プリミティブ値ãŒãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã¦ï¼Œã™ãã«ã‚¢ãƒ³ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã‚‹ (BX_BOXING_IMMEDIATELY_UNBOXED)¶
A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing.
Bx: プリミティブ値ãŒãƒ—リミティブ型ã®åž‹å¤‰æ›ã‚’ã™ã‚‹ãŸã‚ã«ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã¦ï¼Œã‚¢ãƒ³ãƒœã‚¯ã‚·ãƒ³ã‚°ã•ã‚Œã‚‹ (BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)¶
A primitive boxed value constructed and then immediately converted into a different primitive type
(e.g., new Double(d).intValue()
). Just perform direct primitive coercion (e.g., (int) d
).
Dm: クラスオブジェクトを得るãŸã‚ã ã‘ã«ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’作æˆã—ã¦ã„るメソッド (DM_NEW_FOR_GETCLASS)¶
This method allocates an object just to call getClass() on it, in order to retrieve the Class object for it. It is simpler to just access the .class property of the class.
Dm: æ•´æ•°ã®ä¹±æ•°ã‚’生æˆã™ã‚‹ãŸã‚ã«ã¯ nextDouble メソッド ã§ã¯ãªã nextInt メソッドを使用ã™ã‚‹ (DM_NEXTINT_VIA_NEXTDOUBLE)¶
If r
is a java.util.Random
, you can generate a random number from 0
to n-1
using r.nextInt(n)
, rather than using (int)(r.nextDouble() * n)
.
The argument to nextInt must be positive. If, for example, you want to generate a random
value from -99 to 0, use -r.nextInt(100)
.
SS: èªã¿å‡ºã•ã‚Œãªã„フィールド (SS_SHOULD_BE_STATIC)¶
This class contains an instance final field that is initialized to a compile-time static value. Consider making the field static.
UuF: 未使用ã®ãƒ•ã‚£ãƒ¼ãƒ«ãƒ‰ (UUF_UNUSED_FIELD)¶
This field is never used. Consider removing it from the class.
UrF: èªã¿å‡ºã•ã‚Œãªã„フィールド (URF_UNREAD_FIELD)¶
This field is never read. Consider removing it from the class.
SIC: static 内部クラスã«ã™ã¹ã (SIC_INNER_SHOULD_BE_STATIC)¶
This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made static.
SIC: static 内部クラスã«ãƒªãƒ•ã‚¡ã‚¯ã‚¿ãƒªãƒ³ã‚°ã§ãã‚‹ã‹ã‚‚ã—ã‚Œãªã„ (SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS)¶
This class is an inner class, but does not use its embedded reference to the object which created it except during construction of the inner object. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made into a static inner class. Since the reference to the outer object is required during construction of the inner instance, the inner class will need to be refactored so as to pass a reference to the outer instance to the constructor for the inner class.
SIC: åå‰ä»˜ã static 内部クラスã«ãƒªãƒ•ã‚¡ã‚¯ã‚¿ãƒªãƒ³ã‚°ã§ãã‚‹ã‹ã‚‚ã—ã‚Œãªã„ (SIC_INNER_SHOULD_BE_STATIC_ANON)¶
This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made into a static inner class. Since anonymous inner classes cannot be marked as static, doing this will require refactoring the inner class so that it is a named inner class.
UPM: private メソッドã¯æ±ºã—ã¦å‘¼ã³å‡ºã•ã‚Œãªã„ (UPM_UNCALLED_PRIVATE_METHOD)¶
This private method is never called. Although it is possible that the method will be invoked through reflection, it is more likely that the method is never used, and should be removed.
SBSC: ループã®ä¸ã§ + を使用ã—ã¦æ–‡å—列を連çµã—ã¦ã„るメソッド (SBSC_USE_STRINGBUFFER_CONCATENATION)¶
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.
Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.
For example:
// This is bad
String s = "";
for (int i = 0; i < field.length; ++i) {
s = s + field[i];
}
// This is better
StringBuffer buf = new StringBuffer();
for (int i = 0; i < field.length; ++i) {
buf.append(field[i]);
}
String s = buf.toString();
IIL: ループã®ä¸ã§ NodeList.getLength() を呼ã³å‡ºã—ã¦ã„るメソッド (IIL_ELEMENTS_GET_LENGTH_IN_LOOP)¶
The method calls NodeList.getLength() inside the loop and NodeList was produced by getElementsByTagName call. This NodeList doesn't store its length, but computes it every time in not very optimal way. Consider storing the length to the variable before the loop.
IIL: ループã®ä¸ã§ prepareStatement を呼ã³å‡ºã—ã¦ã„るメソッド (IIL_PREPARE_STATEMENT_IN_LOOP)¶
The method calls Connection.prepareStatement inside the loop passing the constant arguments. If the PreparedStatement should be executed several times there's no reason to recreate it for each loop iteration. Move this call outside of the loop.
IIL: ループã®ä¸ã§ Pattern.compile を呼ã³å‡ºã—ã¦ã„るメソッド (IIL_PATTERN_COMPILE_IN_LOOP)¶
The method calls Pattern.compile inside the loop passing the constant arguments. If the Pattern should be used several times there's no reason to compile it for each loop iteration. Move this call outside of the loop or even into static final field.
IIL: ループã®ä¸ã§æ£è¦è¡¨ç¾ã‚’コンパイルã—ã¦ã„るメソッド (IIL_PATTERN_COMPILE_IN_LOOP_INDIRECT)¶
The method creates the same regular expression inside the loop, so it will be compiled every iteration. It would be more optimal to precompile this regular expression using Pattern.compile outside of the loop.
IIO: String.indexOf(String) ã®éžåŠ¹çŽ‡çš„ãªä½¿ç”¨ (IIO_INEFFICIENT_INDEX_OF)¶
This code passes a constant string of length 1 to String.indexOf().
It is more efficient to use the integer implementations of String.indexOf().
f. e. call myString.indexOf('.')
instead of myString.indexOf(".")
IIO: String.lastIndexOf(String) ã®éžåŠ¹çŽ‡çš„ãªä½¿ç”¨ (IIO_INEFFICIENT_LAST_INDEX_OF)¶
This code passes a constant string of length 1 to String.lastIndexOf().
It is more efficient to use the integer implementations of String.lastIndexOf().
f. e. call myString.lastIndexOf('.')
instead of myString.lastIndexOf(".")
ITA: é•·ã•ãŒ0ã®é…列ã®å¼•æ•°ã§ toArray メソッドを使用ã—ã¦ã„るメソッド (ITA_INEFFICIENT_TO_ARRAY)¶
This method uses the toArray() method of a collection derived class, and passes
in a zero-length prototype array argument. It is more efficient to use
myCollection.toArray(new Foo[myCollection.size()])
If the array passed in is big enough to store all of the
elements of the collection, then it is populated and returned
directly. This avoids the need to create a second array
(by reflection) to return as the result.
WMI: entrySet イテレータã§ã¯ãªã効率ãŒæ‚ªã„ keySet イテレータを使用ã—ã¦ã„ã‚‹ (WMI_WRONG_MAP_ITERATOR)¶
This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
UM: 定数値㧠Math クラス㮠static メソッドを呼ã³å‡ºã—ã¦ã„るメソッド (UM_UNNECESSARY_MATH)¶
This method uses a static method from java.lang.Math on a constant value. This method's result in this case, can be determined statically, and is faster and sometimes more accurate to just use the constant. Methods detected are:
Method | Parameter |
---|---|
abs | -any- |
acos | 0.0 or 1.0 |
asin | 0.0 or 1.0 |
atan | 0.0 or 1.0 |
atan2 | 0.0 |
cbrt | 0.0 or 1.0 |
ceil | -any- |
cos | 0.0 |
cosh | 0.0 |
exp | 0.0 or 1.0 |
expm1 | 0.0 |
floor | -any- |
log | 0.0 or 1.0 |
log10 | 0.0 or 1.0 |
rint | -any- |
round | -any- |
sin | 0.0 |
sinh | 0.0 |
sqrt | 0.0 or 1.0 |
tan | 0.0 |
tanh | 0.0 |
toDegrees | 0.0 or 1.0 |
toRadians | 0.0 |
IMA: 所有クラス㮠private メンãƒå¤‰æ•°ã«ã‚¢ã‚¯ã‚»ã‚¹ã—ã¦ã„るメソッド (IMA_INEFFICIENT_MEMBER_ACCESS)¶
This method of an inner class reads from or writes to a private member variable of the owning class, or calls a private method of the owning class. The compiler must generate a special method to access this private member, causing this to be less efficient. Relaxing the protection of the member variable or method will allow the compiler to treat this as a normal access.
ã‚»ã‚ュリティ (SECURITY)¶
A use of untrusted input in a way that could create a remotely exploitable security vulnerability.
XSS: å射型クãƒã‚¹ã‚µã‚¤ãƒˆã‚¹ã‚¯ãƒªãƒ—ティング脆弱性ãŒã‚¨ãƒ©ãƒ¼ãƒšãƒ¼ã‚¸ã«ã‚るサーブレット (XSS_REQUEST_PARAMETER_TO_SEND_ERROR)¶
This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.
SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.
XSS: å射型クãƒã‚¹ã‚µã‚¤ãƒˆã‚¹ã‚¯ãƒªãƒ—ティング脆弱性ãŒã‚るサーブレット (XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER)¶
This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.
SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.
XSS: å射型クãƒã‚¹ã‚µã‚¤ãƒˆã‚¹ã‚¯ãƒªãƒ—ティング脆弱性ãŒã‚ã‚‹ JSP (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)¶
This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.
SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.
HRS: HTTP レスãƒãƒ³ã‚¹ã‚¹ãƒ—リッティング脆弱性 (HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)¶
This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information.
SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool.
HRS: ä¿¡é ¼ã§ããªã„入力ã‹ã‚‰å½¢æˆã•ã‚ŒãŸ HTTP cookie (HRS_REQUEST_PARAMETER_TO_COOKIE)¶
This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information.
SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool.
PT: サーブレットã®çµ¶å¯¾ãƒ‘ストラãƒãƒ¼ã‚µãƒ« (PT_ABSOLUTE_PATH_TRAVERSAL)¶
The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/36.html for more information.
SpotBugs looks only for the most blatant, obvious cases of absolute path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn't report. If you are concerned about absolute path traversal, you should seriously consider using a commercial static analysis or pen-testing tool.
PT: サーブレットã®ç›¸å¯¾ãƒ‘ストラãƒãƒ¼ã‚µãƒ« (PT_RELATIVE_PATH_TRAVERSAL)¶
The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/23.html for more information.
SpotBugs looks only for the most blatant, obvious cases of relative path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn't report. If you are concerned about relative path traversal, you should seriously consider using a commercial static analysis or pen-testing tool.
Dm: ãƒãƒ¼ãƒ‰ã‚³ãƒ¼ãƒ‰ã•ã‚ŒãŸå®šæ•°ãƒ‡ãƒ¼ã‚¿ãƒ™ãƒ¼ã‚¹ãƒ‘スワード (DMI_CONSTANT_DB_PASSWORD)¶
This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password.
Dm: 空ã®ãƒ‡ãƒ¼ã‚¿ãƒ™ãƒ¼ã‚¹ãƒ‘スワード (DMI_EMPTY_DB_PASSWORD)¶
This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password.
SQL: SQL ã® Statement ã® execute ã¾ãŸã¯ addBatch メソッドã«å®šæ•°ã§ã¯ãªã„æ–‡å—列を渡ã—ã¦ã„ã‚‹ (SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)¶
The method invokes the execute or addBatch method on an SQL statement with a String that seems to be dynamically generated. Consider using a prepared statement instead. It is more efficient and less vulnerable to SQL injection attacks.
SQL: PreparedStatement ãŒå®šæ•°ã§ã¯ãªã„æ–‡å—列ã‹ã‚‰ç”Ÿæˆã•ã‚Œã¦ã„ã‚‹ (SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)¶
The code creates an SQL prepared statement from a nonconstant String. If unchecked, tainted data from a user is used in building this String, SQL injection could be used to make the prepared statement do something unexpected and undesirable.
å±ãªã„コード (STYLE)¶
code that is confusing, anomalous, or written in a way that leads itself to errors. Examples include dead local stores, switch fall through, unconfirmed casts, and redundant null check of value known to be null. More false positives accepted. In previous versions of SpotBugs, this category was known as Style.
CAA: フィールドã¸ã®å…±å¤‰é…列代入 (CAA_COVARIANT_ARRAY_FIELD)¶
Array of covariant type is assigned to a field. This is confusing and may lead to ArrayStoreException at runtime if the reference of some other type will be stored in this array later like in the following code:
Number[] arr = new Integer[10];
arr[0] = 1.0;
Consider changing the type of created array or the field type.
CAA: 共変é…列ãŒãƒ¡ã‚½ãƒƒãƒ‰ã‹ã‚‰è¿”ã•ã‚Œã‚‹ (CAA_COVARIANT_ARRAY_RETURN)¶
Array of covariant type is returned from the method. This is confusing and may lead to ArrayStoreException at runtime if the calling code will try to store the reference of some other type in the returned array.
Consider changing the type of created array or the method return type.
CAA: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¸ã®å…±å¤‰é…列代入 (CAA_COVARIANT_ARRAY_LOCAL)¶
Array of covariant type is assigned to a local variable. This is confusing and may lead to ArrayStoreException at runtime if the reference of some other type will be stored in this array later like in the following code:
Number[] arr = new Integer[10];
arr[0] = 1.0;
Consider changing the type of created array or the local variable type.
Dm: サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„ãªã„メソッドã®å‘¼ã³å‡ºã— (DMI_UNSUPPORTED_METHOD)¶
All targets of this method invocation throw an UnsupportedOperationException.
Dm: Thread オブジェクト㌠Runnable ãŒæœŸå¾…ã•ã‚Œã¦ã„ã‚‹ã¨ã“ã‚ã«æ¸¡ã•ã‚Œã¦ã„ã‚‹ (DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED)¶
A Thread object is passed as a parameter to a method where a Runnable is expected. This is rather unusual, and may indicate a logic error or cause unexpected behavior.
NP: readLine メソッドã®çµæžœãŒ null ãªã®ã‹ç¢ºã‹ã‚ãªã„ã§å€¤ã‚’利用ã—ã¦ã„ã‚‹ (NP_DEREFERENCE_OF_READLINE_VALUE)¶
The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception.
NP: readLine メソッドã®çµæžœã‚’ã™ãã«åˆ©ç”¨ã—ã¦ã„ã‚‹ (NP_IMMEDIATE_DEREFERENCE_OF_READLINE)¶
The result of invoking readLine() is immediately dereferenced. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception.
RV: 符å·ä»˜ã32ビット整数ã®ä¹±æ•°ã®å‰°ä½™ (RV_REM_OF_RANDOM_INT)¶
This code generates a random signed integer and then computes the remainder of that value modulo another value. Since the random number can be negative, the result of the remainder operation can also be negative. Be sure this is intended, and strongly consider using the Random.nextInt(int) method instead.
RV: ãƒãƒƒã‚·ãƒ¥ã‚³ãƒ¼ãƒ‰ã®å‰°ä½™ã¯è² ã‹ã‚‚ã—ã‚Œãªã„ (RV_REM_OF_HASHCODE)¶
This code computes a hashCode, and then computes the remainder of that value modulo another value. Since the hashCode can be negative, the result of the remainder operation can also be negative.
Assuming you want to ensure that the result of your computation is nonnegative,
you may need to change your code.
If you know the divisor is a power of 2,
you can use a bitwise and operator instead (i.e., instead of
using x.hashCode()%n
, use x.hashCode()&(n-1)
).
This is probably faster than computing the remainder as well.
If you don't know that the divisor is a power of 2, take the absolute
value of the result of the remainder operation (i.e., use
Math.abs(x.hashCode()%n)
).
Eq: 異常㪠equals メソッド (EQ_UNUSUAL)¶
This class doesn't do any of the patterns we recognize for checking that the type of the argument
is compatible with the type of the this
object. There might not be anything wrong with
this code, but it is worth reviewing.
Eq: スーパークラス㮠equals メソッドをオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã—ã¦ã„ãªã„クラス (EQ_DOESNT_OVERRIDE_EQUALS)¶
This class extends a class that defines an equals method and adds fields, but doesn't define an equals method itself. Thus, equality on instances of this class will ignore the identity of the subclass and the added fields. Be sure this is what is intended, and that you don't need to override the equals method. Even if you don't need to override the equals method, consider overriding it anyway to document the fact that the equals method for the subclass just return the result of invoking super.equals(o).
NS: éžçŸçµ¡è«–ç†ã®ç–‘ã‚ã—ã„使用 (NS_NON_SHORT_CIRCUIT)¶
This code seems to be using non-short-circuit logic (e.g., & or |) rather than short-circuit logic (&& or ||). Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error.
See the Java Language Specification for details.
NS: 潜在的ãªéžçŸçµ¡è«–ç†ã®å±é™ºãªä½¿ç”¨ (NS_DANGEROUS_NON_SHORT_CIRCUIT)¶
This code seems to be using non-short-circuit logic (e.g., & or |) rather than short-circuit logic (&& or ||). In addition, it seem possible that, depending on the value of the left hand side, you might not want to evaluate the right hand side (because it would have side effects, could cause an exception or could be expensive.
Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error.
See the Java Language Specification for details.
IC: åˆæœŸåŒ–ãŒå¾ªç’°ã—ã¦ã„ã‚‹ (IC_INIT_CIRCULARITY)¶
A circularity was detected in the static initializers of the two classes referenced by the bug instance. Many kinds of unexpected behavior may arise from such circularity.
IA: 潜在的ãªç¶™æ‰¿ã•ã‚ŒãŸãƒ¡ã‚½ãƒƒãƒ‰ãªã®ã‹å¤–部ã®ãƒ¡ã‚½ãƒƒãƒ‰ãªã®ã‹ã‚ã„ã¾ã„ãªãƒ¡ã‚½ãƒƒãƒ‰ã®å‘¼ã³å‡ºã— (IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD)¶
An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class.
For example, you invoke foo(17)
, which is defined in both a superclass and in an outer method.
By the Java semantics,
it will be resolved to invoke the inherited method, but this may not be what
you intend.
If you really intend to invoke the inherited method, invoke it by invoking the method on super (e.g., invoke super.foo(17)), and thus it will be clear to other readers of your code and to SpotBugs that you want to invoke the inherited method, not the method in the outer class.
If you call this.foo(17)
, then the inherited method will be invoked. However, since SpotBugs only looks at
classfiles, it
can't tell the difference between an invocation of this.foo(17)
and foo(17)
, it will still
complain about a potential ambiguous invocation.
Se: サブクラスã§ç¶™æ‰¿ã§ããªã„ private 㪠readResolve メソッド (SE_PRIVATE_READ_RESOLVE_NOT_INHERITED)¶
This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses. This might be intentional and OK, but should be reviewed to ensure it is what is intended.
Se: Serializable ã§ã¯ãªã„クラス㮠transient フィールド (SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS)¶
The field is marked as transient, but the class isn't Serializable, so marking it as transient has absolutely no effect. This may be leftover marking from a previous version of the code in which the class was transient, or it may indicate a misunderstanding of how serialization works.
SF: 1ã¤ã® case ãŒæ¬¡ã® case ã¸ã¨é€šã‚ŠæŠœã‘ã‚‹ switch 文を見ã¤ã‘㟠(SF_SWITCH_FALLTHROUGH)¶
This method contains a switch statement where one case branch will fall through to the next case. Usually you need to end this case with a break or return.
SF: default ãŒãªã„ switch 文を見ã¤ã‘㟠(SF_SWITCH_NO_DEFAULT)¶
This method contains a switch statement where default case is missing. Usually you need to provide a default case.
Because the analysis only looks at the generated bytecode, this warning can be incorrect triggered if the default case is at the end of the switch statement and the switch statement doesn't contain break statements for other cases.
UuF: 未使用㮠public ã¾ãŸã¯ protected フィールド (UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD)¶
This field is never used. The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.
UrF: èªã¿å‡ºã•ã‚Œãªã„ public ã¾ãŸã¯ protected フィールド (URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD)¶
This field is never read. The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.
QF: 複雑ã‹å·§å¦™ã‹é–“é•ã£ãŸã‚¤ãƒ³ã‚¯ãƒªãƒ¡ãƒ³ãƒˆã® for ループ (QF_QUESTIONABLE_FOR_LOOP)¶
Are you sure this for loop is incrementing the correct variable? It appears that another variable is being initialized and checked by the for loop.
NP: 書ãè¾¼ã¾ã‚Œã¦ã„ãªã„ public ã¾ãŸã¯ protected フィールドã®èªã¿å‡ºã— (NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)¶
The program is dereferencing a public or protected field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.
UwF: コンストラクタã§åˆæœŸåŒ–ã•ã‚Œã¦ã„ãªã„フィールドを null ãƒã‚§ãƒƒã‚¯ãªã—㧠null 値を利用ã—ã¦ã„ã‚‹ (UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)¶
This field is never initialized within any constructor, and is therefore could be null after the object is constructed. Elsewhere, it is loaded and dereferenced without a null check. This could be a either an error or a questionable design, since it means a null pointer exception will be generated if that field is dereferenced before being initialized.
UwF: 書ãè¾¼ã¾ã¦ã‚Œã„ãªã„ public ã¾ãŸã¯ protected フィールド (UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)¶
No writes were seen to this public/protected field. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.
UC: å½¹ã«ç«‹ãŸãªã„空ã§ã¯ãªã„ void メソッド (UC_USELESS_VOID_METHOD)¶
Our analysis shows that this non-empty void method does not actually perform any useful work. Please check it: probably there's a mistake in its code or its body can be fully removed.
We are trying to reduce the false positives as much as possible, but in some cases this warning might be wrong. Common false-positive cases include:
- The method is intended to trigger loading of some class which may have a side effect.
- The method is intended to implicitly throw some obscure exception.
UC: æ¡ä»¶ã¯åŠ¹æžœãŒãªã„ (UC_USELESS_CONDITION)¶
This condition always produces the same result as the value of the involved variable that was narrowed before. Probably something else was meant or the condition can be removed.
UC: æ¡ä»¶ã¯å¤‰æ•°åž‹ã®ãŸã‚ã«åŠ¹æžœãŒãªã„ (UC_USELESS_CONDITION_TYPE)¶
This condition always produces the same result due to the type range of the involved variable. Probably something else was meant or the condition can be removed.
UC: å½¹ã«ç«‹ãŸãªã„オブジェクトを作æˆã—㟠(UC_USELESS_OBJECT)¶
Our analysis shows that this object is useless. It's created and modified, but its value never go outside of the method or produce any side-effect. Either there is a mistake and object was intended to be used or it can be removed.
This analysis rarely produces false-positives. Common false-positive cases include:
- This object used to implicitly throw some obscure exception.
- This object used as a stub to generalize the code.
- This object used to hold strong references to weak/soft-referenced objects.
UC: å½¹ã«ç«‹ãŸãªã„オブジェクトをスタックã§ä½œæˆã—㟠(UC_USELESS_OBJECT_STACK)¶
This object is created just to perform some modifications which don't have any side-effect. Probably something else was meant or the object can be removed.
RV: メソッドã¯æˆ»ã‚Šå€¤ã‚’無視ã—ã¦ã„ã¾ã™ã€‚ã“ã‚Œã¯é–“é•ã„ã§ã¯ãªã„ã§ã™ã‹? (RV_RETURN_VALUE_IGNORED_INFERRED)¶
This code calls a method and ignores the return value. The return value
is the same type as the type the method is invoked on, and from our analysis it looks
like the return value might be important (e.g., like ignoring the
return value of String.toLowerCase()
).
We are guessing that ignoring the return value might be a bad idea just from a simple analysis of the body of the method. You can use a @CheckReturnValue annotation to instruct SpotBugs as to whether ignoring the return value of this method is important or acceptable.
Please investigate this closely to decide whether it is OK to ignore the return value.
RV: 副作用ãŒãªã„メソッドã®æˆ»ã‚Šå€¤ã¯ç„¡è¦–ã•ã‚Œã‚‹ (RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT)¶
This code calls a method and ignores the return value. However our analysis shows that the method (including its implementations in subclasses if any) does not produce any effect other than return value. Thus this call can be removed.
We are trying to reduce the false positives as much as possible, but in some cases this warning might be wrong. Common false-positive cases include:
- The method is designed to be overridden and produce a side effect in other projects which are out of the scope of the analysis.
- The method is called to trigger the class loading which may have a side effect.
- The method is called just to get some exception.
If you feel that our assumption is incorrect, you can use a @CheckReturnValue annotation to instruct SpotBugs that ignoring the return value of this method is acceptable.
RV: String.indexOf ã®çµæžœãŒæ£ã‹ã©ã†ã‹ç¢ºã‹ã‚ã¦ã„ã‚‹ (RV_CHECK_FOR_POSITIVE_INDEXOF)¶
The method invokes String.indexOf and checks to see if the result is positive or non-positive. It is much more typical to check to see if the result is negative or non-negative. It is positive only if the substring checked for occurs at some place other than at the beginning of the String.
RV: readLine メソッドã®çµæžœã‚’ null ã§ã¯ãªã„ã®ã‹ç¢ºã‹ã‚ãŸå¾Œã§æ¨ã¦ã¦ã„ã‚‹ (RV_DONT_JUST_NULL_CHECK_READLINE)¶
The value returned by readLine is discarded after checking to see if the return value is non-null. In almost all situations, if the result is non-null, you will want to use that non-null value. Calling readLine again will give you a different line.
NP: ãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ã¯ éž null ã§ãªã‘ã‚Œã°ãªã‚‰ãªã„㌠null å¯èƒ½ã¨ã—ã¦ãƒžãƒ¼ã‚¯ã•ã‚Œã¦ã„ã‚‹ (NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE)¶
This parameter is always used in a way that requires it to be non-null, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong.
NP: null ã«ãªã£ã¦ã„ã‚‹å¯èƒ½æ€§ãŒã‚るメソッドã®æˆ»ã‚Šå€¤ã‚’利用ã—ã¦ã„ã‚‹ (NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)¶
The return value from a method is dereferenced without a null check,
and the return value of that method is one that should generally be checked
for null. This may lead to a NullPointerException
when the code is executed.
NP: null 値を実行ä¸å¯èƒ½ã‹ã‚‚ã—ã‚Œãªã„分å²ã§åˆ©ç”¨ã—ã¦ã„ã‚‹å¯èƒ½æ€§ãŒã‚ã‚‹ (NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE)¶
There is a branch of statement that, if executed, guarantees that
a null value will be dereferenced, which
would generate a NullPointerException
when the code is executed.
Of course, the problem might be that the branch or statement is infeasible and that
the null pointer exception can't ever be executed; deciding that is beyond the ability of SpotBugs.
Due to the fact that this value had been previously tested for nullness,
this is a definite possibility.
NP: null ã¨ã‚ã‹ã£ã¦ã„る値ã®ãƒãƒ¼ãƒ‰ (NP_LOAD_OF_KNOWN_NULL_VALUE)¶
The variable referenced at this point is known to be null due to an earlier check against null. Although this is valid, it might be a mistake (perhaps you intended to refer to a different variable, or perhaps the earlier check to see if the variable is null should have been a check to see if it was non-null).
PZLA: null ã§ã¯ãªãé•·ã•ãŒ0ã®é…列を返ã™ã“ã¨ã‚’検討ã™ã‚‹ (PZLA_PREFER_ZERO_LENGTH_ARRAYS)¶
It is often a better design to return a length zero array rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.
On the other hand, using null to indicate
"there is no answer to this question" is probably appropriate.
For example, File.listFiles()
returns an empty list
if given a directory containing no files, and returns null if the file
is not a directory.
UCF: å½¹ã«ç«‹ãŸãªã„制御フãƒãƒ¼ (UCF_USELESS_CONTROL_FLOW)¶
This method contains a useless control flow statement, where
control flow continues onto the same place regardless of whether or not
the branch is taken. For example,
this is caused by having an empty statement
block for an if
statement:
if (argv.length == 0) {
// TODO: handle this case
}
UCF: 次ã®è¡Œã¸ç¶šãã ã‘ã®å½¹ã«ç«‹ãŸãªã„制御フãƒãƒ¼ (UCF_USELESS_CONTROL_FLOW_NEXT_LINE)¶
This method contains a useless control flow statement in which control
flow follows to the same or following line regardless of whether or not
the branch is taken.
Often, this is caused by inadvertently using an empty statement as the
body of an if
statement, e.g.:
if (argv.length == 1);
System.out.println("Hello, " + argv[0]);
RCN: null ã¨ã‚ã‹ã£ã¦ã„る値ã®å†—長㪠null ãƒã‚§ãƒƒã‚¯ (RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE)¶
This method contains a redundant check of a known null value against the constant null.
RCN: null ã§ã¯ãªã„ã“ã¨ãŒã‚ã‹ã£ã¦ã„る値ã®å†—長㪠null ãƒã‚§ãƒƒã‚¯ (RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE)¶
This method contains a redundant check of a known non-null value against the constant null.
RCN: 2ã¤ã® null 値ã®å†—é•·ãªæ¯”較 (RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES)¶
This method contains a redundant comparison of two references known to both be definitely null.
RCN: éž null 値㨠null 値ã¨ã®å†—é•·ãªæ¯”較 (RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE)¶
This method contains a reference known to be non-null with another reference known to be null.
FS: Boolean åž‹ã§ã¯ãªã„引数を ï¼…b 書å¼æŒ‡ç¤ºåを使用ã—ã¦ãƒ•ã‚©ãƒ¼ãƒžãƒƒãƒˆã—ã¦ã„ã‚‹ (VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN)¶
An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an exception; instead, it will print true for any non-null value, and false for null. This feature of format strings is strange, and may not be what you intended.
SA: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã®è‡ªå·±ä»£å…¥ (SA_LOCAL_SELF_ASSIGNMENT)¶
This method contains a self assignment of a local variable; e.g.
public void foo() {
int x = 3;
x = x;
}
Such assignments are useless, and may indicate a logic error or typo.
INT: 1を法ã¨ã™ã‚‹æ•´æ•°ã®å‰°ä½™ (INT_BAD_REM_BY_1)¶
Any expression (exp % 1) is guaranteed to always return zero. Did you mean (exp & 1) or (exp % 2) instead?
INT: 整数値ã®ç„¡æ„味ãªæ¯”較 (INT_VACUOUS_COMPARISON)¶
There is an integer comparison that always returns the same value (e.g., x <= Integer.MAX_VALUE).
INT: 整数値ã®ç„¡æ„味ãªãƒ“ットマスク演算 (INT_VACUOUS_BIT_OPERATION)¶
This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work
(e.g., v & 0xffffffff
).
SA: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã®äºŒé‡ä»£å…¥ (SA_LOCAL_DOUBLE_ASSIGNMENT)¶
This method contains a double assignment of a local variable; e.g.
public void foo() {
int x,y;
x = x = 17;
}
Assigning the same value to a variable twice is useless, and may indicate a logic error or typo.
SA: フィールドã®äºŒé‡ä»£å…¥ (SA_FIELD_DOUBLE_ASSIGNMENT)¶
This method contains a double assignment of a field; e.g.
int x,y;
public void foo() {
x = x = 17;
}
Assigning to a field twice is useless, and may indicate a logic error or typo.
DLS: return æ–‡ã«å½¹ã«ç«‹ãŸãªã„代入ãŒã‚ã‚‹ (DLS_DEAD_LOCAL_STORE_IN_RETURN)¶
This statement assigns to a local variable in a return statement. This assignment has effect. Please verify that this statement does the right thing.
DLS: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¸ã®ç„¡åŠ¹ãªä»£å…¥ (DLS_DEAD_LOCAL_STORE)¶
This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used.
Note that Sun's javac compiler often generates dead stores for final local variables. Because SpotBugs is a bytecode-based tool, there is no easy way to eliminate these false positives.
DLS: フィールドをé®ã‚‹ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¸ã®ç„¡åŠ¹ãªä»£å…¥ (DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD)¶
This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. There is a field with the same name as the local variable. Did you mean to assign to that variable instead?
DLS: ãƒãƒ¼ã‚«ãƒ«å¤‰æ•°ã¸ã®ç„¡åŠ¹ãª null 代入 (DLS_DEAD_LOCAL_STORE_OF_NULL)¶
The code stores null into a local variable, and the stored value is not read. This store may have been introduced to assist the garbage collector, but as of Java SE 6.0, this is no longer needed or useful.
REC: 例外ãŒã‚¹ãƒãƒ¼ã•ã‚Œãªã„ã®ã«ä¾‹å¤–ã‚’ã‚ャッãƒã—ã¦ã„ã‚‹ (REC_CATCH_EXCEPTION)¶
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
FE: 浮動å°æ•°ç‚¹ã®ç‰ä¾¡æ€§ã®ãŸã‚ã®ãƒ†ã‚¹ãƒˆ (FE_FLOATING_POINT_EQUALITY)¶
This operation compares two floating point values for equality.
Because floating point calculations may involve rounding,
calculated float and double values may not be accurate.
For values that must be precise, such as monetary values,
consider using a fixed-precision type such as BigDecimal.
For values that need not be precise, consider comparing for equality
within some range, for example:
if ( Math.abs(x - y) < .0000001 )
.
See the Java Language Specification, section 4.2.4.
CD: クラス間ã®å¾ªç’°ä¾å˜é–¢ä¿‚ã®ãƒ†ã‚¹ãƒˆ (CD_CIRCULAR_DEPENDENCY)¶
This class has a circular dependency with other classes. This makes building these classes difficult, as each is dependent on the other to build correctly. Consider using interfaces to break the hard dependency.
RI: スーパークラスã¨åŒã˜ã‚¤ãƒ³ã‚¿ãƒ•ã‚§ãƒ¼ã‚¹ã‚’実装ã—ã¦ã„るクラス (RI_REDUNDANT_INTERFACES)¶
This class declares that it implements an interface that is also implemented by a superclass. This is redundant because once a superclass implements an interface, all subclasses by default also implement this interface. It may point out that the inheritance hierarchy has changed since this class was created, and consideration should be given to the ownership of the interface's implementation.
MTIA: Struts Action ã‚’æ‹¡å¼µã—ãŸã‚¯ãƒ©ã‚¹ã§ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹å¤‰æ•°ã®ä½¿ç”¨ (MTIA_SUSPECT_STRUTS_INSTANCE_FIELD)¶
This class extends from a Struts Action class, and uses an instance member variable. Since only one instance of a struts Action class is created by the Struts framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables. Only instance fields that are written outside of a monitor are reported.
MTIA: Servlet クラスを拡張ã—ãŸã‚¯ãƒ©ã‚¹ã§ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹å¤‰æ•°ã®ä½¿ç”¨ (MTIA_SUSPECT_SERVLET_INSTANCE_FIELD)¶
This class extends from a Servlet class, and uses an instance member variable. Since only one instance of a Servlet class is created by the J2EE framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables.
PS: 公開インタフェースã§åŒæœŸåŒ–ã¨ã‚»ãƒžãƒ•ã‚©ã‚’暴露ã™ã‚‹ã‚¯ãƒ©ã‚¹ (PS_PUBLIC_SEMAPHORES)¶
This class uses synchronization along with wait(), notify() or notifyAll() on itself (the this reference). Client classes that use this class, may, in addition, use an instance of this class as a synchronizing object. Because two classes are using the same object for synchronization, Multithread correctness is suspect. You should not synchronize nor call semaphore methods on a public reference. Consider using a internal private member variable to control synchronization.
ICAST: æ•´æ•°ä¹—ç®—ã®çµæžœã‚’ long ã«ã‚ャストã—ã¦ã„ã‚‹ (ICAST_INTEGER_MULTIPLY_CAST_TO_LONG)¶
This code performs integer multiply and then converts the result to a long, as in:
long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; }
If the multiplication is done using long arithmetic, you can avoid the possibility that the result will overflow. For example, you could fix the above code to:
long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; }
or
static final long MILLISECONDS_PER_DAY = 24L*3600*1000;
long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; }
ICAST: æ•´æ•°ã®é™¤ç®—ã®çµæžœã‚’ double ã¾ãŸã¯ float ã«ã‚ャストã—ã¦ã„ã‚‹ (ICAST_IDIV_CAST_TO_DOUBLE)¶
This code casts the result of an integral division (e.g., int or long division) operation to double or float. Doing division on integers truncates the result to the integer value closest to zero. The fact that the result was cast to double suggests that this precision should have been retained. What was probably meant was to cast one or both of the operands to double before performing the division. Here is an example:
int x = 2;
int y = 5;
// Wrong: yields result 0.0
double value1 = x / y;
// Right: yields result 0.4
double value2 = x / (double) y;
BC: 具象コレクションã¸ã®ç–‘ã‚ã—ã„ã‚ャスト (BC_BAD_CAST_TO_CONCRETE_COLLECTION)¶
This code casts an abstract collection (such as a Collection, List, or Set) to a specific concrete implementation (such as an ArrayList or HashSet). This might not be correct, and it may make your code fragile, since it makes it harder to switch to other concrete implementations at a future point. Unless you have a particular reason to do so, just use the abstract collection class.
BC: 未ãƒã‚§ãƒƒã‚¯/未確èªã®ã‚ャスト (BC_UNCONFIRMED_CAST)¶
This cast is unchecked, and not all instances of the type casted from can be cast to the type it is being cast to. Check that your program logic ensures that this cast will not fail.
BC: メソッドã‹ã‚‰ã®æˆ»ã‚Šå€¤ã®æœªãƒã‚§ãƒƒã‚¯/未確èªã®ã‚ャスト (BC_UNCONFIRMED_CAST_OF_RETURN_VALUE)¶
This code performs an unchecked cast of the return value of a method. The code might be calling the method in such a way that the cast is guaranteed to be safe, but SpotBugs is unable to verify that the cast is safe. Check that your program logic ensures that this cast will not fail.
BC: 常㫠true を返㙠instanceof (BC_VACUOUS_INSTANCEOF)¶
This instanceof test will always return true (unless the value being tested is null). Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error. If you really want to test the value for being null, perhaps it would be clearer to do better to do a null test rather than an instanceof test.
BC: 抽象コレクションã¸ã®ç–‘ã‚ã—ã„ã‚ャスト (BC_BAD_CAST_TO_ABSTRACT_COLLECTION)¶
This code casts a Collection to an abstract collection
(such as List
, Set
, or Map
).
Ensure that you are guaranteed that the object is of the type
you are casting to. If all you need is to be able
to iterate through a collection, you don't need to cast it to a Set or List.
IM: è² æ•°ã§æ©Ÿèƒ½ã—ãªã„奇数ãƒã‚§ãƒƒã‚¯ (IM_BAD_CHECK_FOR_ODD)¶
The code uses x % 2 == 1 to check to see if a value is odd, but this won't work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x & 1 == 1, or x % 2 != 0.
IM: å¹³å‡ã®è¨ˆç®—ã¯ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒãƒ¼ã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚‹ (IM_AVERAGE_COMPUTATION_COULD_OVERFLOW)¶
The code computes the average of two integers using either division or signed right shift,
and then uses the result as the index of an array.
If the values being averaged are very large, this can overflow (resulting in the computation
of a negative average). Assuming that the result is intended to be nonnegative, you
can use an unsigned right shift instead. In other words, rather that using (low+high)/2
,
use (low+high) >>> 1
This bug exists in many earlier implementations of binary search and merge sort. Martin Buchholz found and fixed it in the JDK libraries, and Joshua Bloch widely publicized the bug pattern.
BSHIFT: 符å·ãªã—å³ã‚·ãƒ•ãƒˆã‚’ short/byte ã«ã‚ャストã—ã¦ã„ã‚‹ (ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT)¶
The code performs an unsigned right shift, whose result is then cast to a short or byte, which discards the upper bits of the result. Since the upper bits are discarded, there may be no difference between a signed and unsigned right shift (depending upon the size of the shift).
DMI: ãƒãƒ¼ãƒ‰ã‚³ãƒ¼ãƒ‰ã•ã‚ŒãŸçµ¶å¯¾ãƒ‘スåã¸ã®å‚ç…§ãŒã‚ã‚‹ (DMI_HARDCODED_ABSOLUTE_FILENAME)¶
This code constructs a File object using a hard coded to an absolute pathname
(e.g., new File("/home/dannyc/workspace/j2ee/src/share/com/sun/enterprise/deployment");
DMI: substring(0) ã®å‘¼ã³å‡ºã—ã¯å…ƒã®å€¤ã‚’返㙠(DMI_USELESS_SUBSTRING)¶
This code invokes substring(0) on a String, which returns the original value.
ST: インスタンスメソッドã‹ã‚‰ static フィールドã¸ã®æ›¸ã込㿠(ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)¶
This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
DMI: ObjectOutput ã«æ›¸ãè¾¼ã¾ã‚Œã‚‹éžç›´åˆ—化å¯èƒ½ã‚ªãƒ–ジェクト (DMI_NONSERIALIZABLE_OBJECT_WRITTEN)¶
This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. If the object is, indeed, non-serializable, an error will result.
DB: 2ã¤ã®åˆ†å²ã®ãŸã‚ã«åŒã˜ã‚³ãƒ¼ãƒ‰ã‚’使用ã—ã¦ã„るメソッド (DB_DUPLICATE_BRANCHES)¶
This method uses the same code to implement two branches of a conditional branch. Check to ensure that this isn't a coding mistake.
DB: switch æ–‡ã®2ã¤ã® case ã®ãŸã‚ã«åŒã˜ã‚³ãƒ¼ãƒ‰ã‚’使用ã—ã¦ã„るメソッド (DB_DUPLICATE_SWITCH_CLAUSES)¶
This method uses the same code to implement two clauses of a switch statement. This could be a case of duplicate code, but it might also indicate a coding mistake.
XFB: XMLインタフェースã®ç‰¹å®šã®å®Ÿè£…ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’作æˆã—ã¦ã„るメソッド (XFB_XML_FACTORY_BYPASS)¶
This method allocates a specific implementation of an xml interface. It is preferable to use the supplied factory classes to create these objects so that the implementation can be changed at runtime. See
- javax.xml.parsers.DocumentBuilderFactory
- javax.xml.parsers.SAXParserFactory
- javax.xml.transform.TransformerFactory
- org.w3c.dom.Document.createXXXX
for details.
USM: 親クラスã®ãƒ¡ã‚½ãƒƒãƒ‰ã«éŽå‰°ã«å§”è²ã—ã¦ã„るメソッド (USM_USELESS_SUBCLASS_METHOD)¶
This derived method merely calls the same superclass method passing in the exact parameters received. This method can be removed, as it provides no additional value.
USM: 実装ã•ã‚ŒãŸã‚¤ãƒ³ã‚¿ãƒ•ã‚§ãƒ¼ã‚¹ã§æ—¢ã«å®šç¾©ã•ã‚ŒãŸæŠ½è±¡ãƒ¡ã‚½ãƒƒãƒ‰ (USM_USELESS_ABSTRACT_METHOD)¶
This abstract method is already defined in an interface that is implemented by this abstract class. This method can be removed, as it provides no additional value.
CI: final ãªã‚¯ãƒ©ã‚¹ãŒ protected フィールドを宣言ã—ã¦ã„ã‚‹ (CI_CONFUSED_INHERITANCE)¶
This class is declared to be final, but declares fields to be protected. Since the class is final, it can not be derived from, and the use of protected is confusing. The access modifier for the field should be changed to private or public to represent the true use for the field.
TQ: 値ã¯åž‹ä¿®é£¾åã‚’å¿…è¦ã¨ã—ãªã„ãŒï¼Œä¸æ˜Žã¨ã—ã¦ãƒžãƒ¼ã‚¯ã•ã‚Œã¦ã„ã‚‹ (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK)¶
A value is used in a way that requires it to be never be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. Either the usage or the annotation is incorrect.
TQ: 値ã¯åž‹ä¿®é£¾åã‚’å¿…è¦ã¨ã—ã¦ã„ã‚‹ãŒï¼Œä¸æ˜Žã¨ã—ã¦ãƒžãƒ¼ã‚¯ã•ã‚Œã¦ã„ã‚‹ (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK)¶
A value is used in a way that requires it to be always be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. Either the usage or the annotation is incorrect.
NP: メソッドã¯æˆ»ã‚Šå€¤ã® nullness アノテーションを緩和ã—ã¦ã„ã‚‹ (NP_METHOD_RETURN_RELAXING_ANNOTATION)¶
A method should always implement the contract of a method it overrides. Thus, if a method takes is annotated as returning a @Nonnull value, you shouldn't override that method in a subclass with a method annotated as returning a @Nullable or @CheckForNull value. Doing so violates the contract that the method shouldn't return null.
NP: メソッドã¯ãƒ‘ラメータ㫠nullness アノテーションを強化ã—ã¦ã„ã‚‹ (NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION)¶
A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter that is marked as @Nullable, you shouldn't override that method in a subclass with a method where that parameter is @Nonnull. Doing so violates the contract that the method should handle a null parameter.
NP: メソッドã¯ãƒ‘ラメータ㫠nullness アノテーションを強化ã—ã¦ã„ã‚‹ (NP_METHOD_PARAMETER_RELAXING_ANNOTATION)¶
A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter that is marked as @Nullable, you shouldn't override that method in a subclass with a method where that parameter is @Nonnull. Doing so violates the contract that the method should handle a null parameter.
Guide for migration from FindBugs 3.0 to SpotBugs 3.1¶
com.google.code.findbugs:findbugs¶
Simply replace com.google.code.findbugs:findbugs
with com.github.spotbugs:spotbugs
.
<!-- for Maven -->
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>3.1.0-RC5</version>
</dependency>
// for Gradle
compileOnly 'com.github.spotbugs:spotbugs:3.1.0-RC5'
com.google.code.findbugs:jsr305¶
JSR305 is already Dormant status, so SpotBugs does not release jsr305
jar file.
Please continue using findbugs’ one.
com.google.code.findbugs:findbugs-annotations¶
Please depend on spotbugs-annotations
instead.
<!-- for Maven -->
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<version>3.1.0-RC5</version>
<optional>true</optional>
</dependency>
// for Gradle
compileOnly 'com.github.spotbugs:spotbugs-annotations:3.1.0-RC5'
com.google.code.findbugs:annotations¶
Please depend on both of spotbugs-annotations
and net.jcip:jcip-annotations:1.0
instead.
<!-- for Maven -->
<dependency>
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<version>1.0</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<version>3.1.0-RC5</version>
<optional>true</optional>
</dependency>
// for Gradle
compileOnly 'net.jcip:jcip-annotations:1.0'
compileOnly 'com.github.spotbugs:spotbugs-annotations:3.1.0-RC5'
FindBugs Ant task¶
Please replace findbugs-ant.jar
with spotbugs-ant.jar
.
<taskdef
resource="edu/umd/cs/findbugs/anttask/tasks.properties"
classpath="path/to/spotbugs-ant.jar" />
<property name="spotbugs.home" value="/path/to/spotbugs/home" />
<target name="spotbugs" depends="jar">
<spotbugs home="${spotbugs.home}"
output="xml"
outputFile="bcel-fb.xml" >
<auxClasspath path="${basedir}/lib/Regex.jar" />
<sourcePath path="${basedir}/src/java" />
<class location="${basedir}/bin/bcel.jar" />
</spotbugs>
</target>
FindBugs Maven plugin¶
Please use com.github.hazendaz.spotbugs:spotbugs-maven-plugin instead of org.codehaus.mojo:findbugs-maven-plugin.
<plugin>
<groupId>com.github.hazendaz.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.0.6</version>
<dependencies>
<!-- overwrite dependency on spotbugs if you want to specify the version of spotbugs -->
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>3.1.0-RC5</version>
</dependency>
</dependencies>
</plugin>
FindBugs Gradle plugin¶
Please use spotbugs plugin found on https://plugins.gradle.org/plugin/com.github.spotbugs
plugins {
id 'com.github.spotbugs' version '1.3'
}
spotbugs {
toolVersion = '3.1.0-RC5'
}
// To generate an HTML report instead of XML
tasks.withType(com.github.spotbugs.SpotBugsTask) {
reports {
xml.enabled = false
html.enabled = true
}
}
FindBugs Eclipse plugin¶
Please use following update site instead.
- https://spotbugs.github.io/eclipse/ (to use stable version, not ready yet)
- https://spotbugs.github.io/eclipse-candidate/ (to use candidate version)
- https://spotbugs.github.io/eclipse-latest/ (to use latest build)