Java Development User Guide
Java Development User Guide
Javadevelopmentuserguide
Contents
1.Javadevelopmentoverview
2.GettingStarted
2.1.Basictutorial
2.1.1.PreparingEclipse
2.1.2.CreatingyourfirstJavaproject
2.1.3.BrowsingJavaelementsusingthepackageexplorer
2.1.4.EditingJavaelements
2.1.4.1.OpeningaJavaeditor
2.1.4.2.Usingquickviews
2.1.4.3.Addingnewmethods
2.1.4.4.Usingcontentassist
2.1.4.5.Identifyingproblemsinyourcode
2.1.4.6.Usingcodetemplates
2.1.4.7.Organizingimportstatements
2.1.4.8.Usingthelocalhistory
2.1.4.9.Extractinganewmethod
2.1.5.CreatingaJavaclass
2.1.6.RenamingJavaelements
2.1.7.MovingandcopyingJavaelements
2.1.8.NavigatetoaJavaelement'sdeclaration
2.1.9.ViewingthetypeHierarchy
2.1.10.Searchingtheworkbench
2.1.11.Runningyourprograms
2.1.12.Debuggingyourprograms
2.1.13.Evaluatingexpressions
2.1.14.Evaluatingsnippets
2.1.15.UsingtheJavabrowsingperspective
2.1.16.WritingandrunningJUnittests
2.2.Projectconfigurationtutorial
2.2.1.Detectingexistinglayout
2.2.2.Organizingsources
2.2.3.Siblingproductsinacommonsourcetree
2.2.4.Overlappingproductsinacommonsourcetree
2.2.5.Productwithnestedtests
2.2.6.Productssharingacommonsourceframework
2.2.7.Productnestingresourcesinoutputdirectory
2.2.8.Projectusingasourceframeworkwithrestrictedaccess
2.3.EclipseandJ2SE5.0
2.4.EclipseandJava7
3.Concepts
3.1.JavaProjects
3.2.JavaBuilder
3.2.1.BuildClasspath
3.2.1.1.InclusionandExclusionPatterns
3.2.1.2.AccessRules
3.2.1.3.ClasspathVariables
3.3.JavaPerspectives
3.4.JavaViews
3.4.1.FilteringinJavaViews
3.4.2.SortinginJavaViews
3.4.3.JavaElementDecorations
3.4.4.PresentationOptionsforJavaViews
3.5.JavaEditor
3.6.QuickFixandAssist
3.7.Templates
3.7.1.Templatevariables
3.8.JavaSearch
3.9.RefactoringSupport
3.10.Debugger
3.11.Scrapbook
3.12.LocalDebugging
3.13.RemoteDebugging
3.14.Breakpoints
3.15.StringExternalization
4.Tasks
4.1.CustomizingtheDebuggerandConsole
4.1.1.Changingtheactiveperspectivewhenlaunching
4.1.2.Changingtheappearanceoftheconsoleview
4.2.CreatingJARFiles
4.2.1.CreatinganewJARfile
4.2.2.Settingadvancedoptions
4.2.3.DefiningtheJARfile'smanifest
4.2.4.RegeneratingaJARFile
4.2.5.CreatinganewrunnableJARfile
4.3.UsingtheLocalHistory
4.3.1.ComparingaJavaelementwithalocalhistoryedition
4.3.2.ReplacingaJavaelementwithalocalhistoryedition
4.3.3.Restoringadeletedworkbenchelement
4.4.ExternalizingStrings
4.4.1.Findingstringstoexternalize
4.4.2.Findingunusedandincorrectlyusedkeysinpropertyfiles
4.5.NavigatingtheWorkbench
4.5.1.Openinganeditorforaselectedelement
4.5.2.ShowinganelementinthePackageExplorerview
4.5.3.OpeningatypeinthePackageExplorerview
4.5.4.Openinganeditoronatype
4.5.5.Openingapackage
4.6.WorkingwithJREs
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 1/322
12/10/2015 Javadevelopmentuserguide
4.6.1.AssigningthedefaultJREfortheworkbench
4.6.2.AddinganewJREdefinition
4.6.3.ChoosingaJREforlaunchingaproject
4.6.4.DeletingaJREdefinition
4.7.RunningandDebugging
4.7.1.Breakpoints
4.7.1.1.AddingLineBreakpoints
4.7.1.2.RemovingLineBreakpoints
4.7.1.3.EnablingandDisablingBreakpoints
4.7.1.4.SettingMethodBreakpoints
4.7.1.5.ApplyingHitCounts
4.7.1.6.ManagingConditionalBreakpoints
4.7.1.7.CatchingJavaExceptions
4.7.1.8.CreatingExceptionBreakpointFilters
4.7.2.LocalDebugging
4.7.2.1.PreparingtoDebug
4.7.2.2.LaunchingaJavaprograminDebugMode
4.7.2.3.SuspendingThreads
4.7.2.4.ResumingThreads
4.7.2.5.Steppingthroughtheexecutionofaprogram
4.7.2.6.InspectingValues
4.7.2.7.Evaluatingexpressions
4.7.3.RemoteDebugging
4.7.3.1.UsingtheremoteJavaapplicationlaunchconfiguration
4.7.3.2.DisconnectingfromaVM
4.7.4.CreatingaJavaapplicationlaunchconfiguration
4.7.5.LaunchingaJavaprogram
4.7.6.LaunchingaJavaapplet
4.7.7.Settingexecutionarguments
4.7.8.Relaunchingaprogram
4.7.9.InspectingmemoryintheMemoryview
4.7.9.1.Addingavariable,expression,orregistertotheMemoryview
4.7.9.2.Addingmultiplememoryrenderingsandremovingrenderings
4.7.9.3.Workingwithmemorymonitors
4.7.9.4.Changingthecontentsofamemorylocation
4.7.9.5.Memoryviewpreferences
4.7.9.6.WorkingwithmultipleMemoryviews
4.7.9.7.RemovingmemorymonitorsfromtheMemoryview
4.8.UsingtheScrapbook
4.8.1.CreatingaJavaScrapbookPage
4.8.2.Inspectingtheresultofevaluatinganexpression
4.8.3.Displayingtheresultofevaluatinganexpression
4.8.4.Runninganexpression
4.8.5.Usingcodeassist
4.8.6.Scrapbookerrorreporting
4.8.6.1.Viewingcompilationerrors
4.8.6.2.Viewingruntimeexceptions
4.9.CompilingJavacode
4.9.1.Usingthebatchcompiler
4.9.2.Usingtheantjavacadapter
4.9.3.Excludingwarnings
4.10.ImprovingJavacodequality
4.10.1.Usingnullannotations
4.10.1.1.Interproceduralnullananlysis
4.10.1.2.Availableannotations
4.10.1.3.Setupofthebuildpath
4.10.1.4.Interpretationofnullannotations
4.10.1.5.Designbycontract:APIspecification
4.10.1.6.Completespecificationusinganextendedtypesystem
4.10.1.7.Compilermessagesexplained
4.10.1.8.Tipsformakingcodebetteranalyzable
4.10.1.9.Tipsforadoptingnullannotations
4.10.2.Usingnulltypeannotations
4.10.2.1.Generics
4.10.2.1.1.Typeparameters
4.10.2.1.2.Typevariables
4.10.2.1.3.Typearguments
4.10.2.2.Inference
4.10.2.3.Morelocations
4.10.2.4.Compatibility
4.10.2.4.1.Syntax
4.10.2.4.2.Projectconfiguration
4.10.2.4.3.Semantics
4.10.2.5.Compilermessagesexplained
4.10.3.Usingexternalnullannotations
4.10.3.1.Structureofexternalannotations
4.10.3.2.Configuringaprojecttouseexternalannotations
4.10.3.3.Creatingexternalannotations
4.10.3.4.Inspectingexternalannotations
4.10.3.5.Declarationannotationsvstypeannotations
4.10.4.Avoidingresourceleaks
4.10.5.Ensuringcompletenessofswitchstatements
4.11.UsingtheFormatterApplication
4.11.1.Runningtheformatterapplication
4.11.2.Generatingaconfigfilefortheformatterapplication
5.Reference
5.1.Breakpoints
5.1.1.ConditionOption
5.1.2.EnabledOption
5.1.3.ExceptionBreakpointCaughtOption
5.1.4.ExceptionBreakpointSuspendonSubclassOption
5.1.5.ExceptionBreakpointUncaughtOption
5.1.6.HitCountOption
5.1.7.MethodBreakpointEntryOption
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 2/322
12/10/2015 Javadevelopmentuserguide
5.1.8.MethodBreakpointExitOption
5.1.9.SuspendPolicyOption
5.1.10.WatchpointModificationOption
5.1.11.WatchpointAccessOption
5.2.MenusandActions
5.2.1.FileMenuActions
5.2.2.EditMenuActions
5.2.3.SourceMenuActions
5.2.4.RefactorMenuActions
5.2.5.NavigateMenuActions
5.2.6.SearchMenuActions
5.2.7.ProjectMenuActions
5.2.8.RunMenuActions
5.2.9.JavaToolbarActions
5.2.10.RunandDebugToolbarActions
5.2.11.JavaEditorActions
5.3.Preferences
5.3.1.Java
5.3.1.1.Appearance
5.3.1.1.1.MemberSortOrder
5.3.1.1.2.TypeFilters
5.3.1.2.BuildPath
5.3.1.2.1.ClasspathVariables
5.3.1.2.2.UserLibraries
5.3.1.3.CodeStyle
5.3.1.3.1.CleanUp
5.3.1.3.2.CodeTemplates
5.3.1.3.3.Formatter
5.3.1.3.4.OrganizeImports
5.3.1.4.Compiler
5.3.1.4.1.Building
5.3.1.4.2.Errors/Warnings
5.3.1.4.3.Javadoc
5.3.1.4.4.TaskTags
5.3.1.5.Debug
5.3.1.5.1.DetailFormatters
5.3.1.5.2.HeapWalking
5.3.1.5.3.LogicalStructures
5.3.1.5.4.PrimitiveDisplayOptions
5.3.1.5.5.StepFiltering
5.3.1.6.Editor
5.3.1.6.1.ContentAssist
5.3.1.6.1.1.Advanced
5.3.1.6.1.2.Favorites
5.3.1.6.2.Folding
5.3.1.6.3.Hovers
5.3.1.6.4.MarkOccurrences
5.3.1.6.5.SaveActions
5.3.1.6.6.SyntaxColoring
5.3.1.6.7.Templates
5.3.1.6.7.1.TemplateEditing
5.3.1.6.8.Typing
5.3.1.7.InstalledJREs
5.3.1.7.1.ExecutionEnvironments
5.3.1.8.JUnit
5.3.1.9.PropertiesFilesEditor
5.3.2.Run/Debug
5.3.2.1.Console
5.3.2.2.Launching
5.3.2.2.1.DefaultLaunchers
5.3.2.2.2.LaunchConfigurations
5.3.2.3.Perspectives
5.3.2.4.StringSubstitution
5.3.2.5.ViewManagement
5.4.PropertyPages
5.4.1.JavadocLocation
5.4.2.JavaBuildPath
5.4.3.JavaCompiler
5.4.4.JavaTaskTags
5.4.5.SourceAttachment
5.4.6.Run/Debug
5.5.Refactoring
5.5.1.RefactorActions
5.5.2.RefactorWizard
5.5.3.ExtractMethodErrors
5.6.Search
5.6.1.JavaSearchTab
5.6.2.JavaSearchActions
5.7.Toolbar
5.7.1.JavaToolbarActions
5.7.2.JavaEditorToolbarActions
5.7.3.RunandDebugToolbarActions
5.8.Views
5.8.1.BreakpointsView
5.8.1.1.Access
5.8.1.2.AddJavaExceptionBreakpoint
5.8.1.3.BreakpointProperties
5.8.1.4.Caught
5.8.1.5.CollapseAll
5.8.1.6.Copy
5.8.1.7.Disable
5.8.1.8.Enable
5.8.1.9.Entry
5.8.1.10.Exit
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 3/322
12/10/2015 Javadevelopmentuserguide
5.8.1.11.ExpandAll
5.8.1.12.ExportBreakpoints
5.8.1.13.GotoFileforBreakpoint
5.8.1.14.GroupBy
5.8.1.15.HitCount
5.8.1.16.ImportBreakpoints
5.8.1.17.LinkwithDebugView
5.8.1.18.Modification
5.8.1.19.Paste
5.8.1.20.RemoveSelectedBreakpoints
5.8.1.21.RemoveAllBreakpoints
5.8.1.22.SelectAll
5.8.1.23.SelectDefaultWorkingSet
5.8.1.24.ShowQualifiedNames
5.8.1.25.ShowSupportedBreakpoints
5.8.1.26.SkipAllBreakpoints
5.8.1.27.SuspendPolicy
5.8.1.28.WorkingSets...
5.8.1.29.Uncaught
5.8.2.ConsoleView
5.8.2.1.CVSConsole
5.8.2.1.1.Copy
5.8.2.1.2.Cut
5.8.2.1.3.Find/Replace
5.8.2.1.4.OpenLink
5.8.2.1.5.Paste
5.8.2.1.6.SelectAll
5.8.2.2.ProcessConsole
5.8.2.2.1.Copy
5.8.2.2.2.Cut
5.8.2.2.3.ConsolePreferences
5.8.2.2.4.Find/Replace
5.8.2.2.5.Paste
5.8.2.2.6.RemoveAllTerminatedLaunches
5.8.2.2.7.RemoveLaunch
5.8.2.2.8.SelectAll
5.8.2.2.9.ShowConsoleWhenStandardOutChanges
5.8.2.2.10.ShowConsoleWhenStandardErrorChanges
5.8.2.2.11.Terminate
5.8.2.3.StacktraceConsole
5.8.2.3.1.AutoformatConsole
5.8.2.3.2.Copy
5.8.2.3.3.Cut
5.8.2.3.4.Find/Replace
5.8.2.3.5.Format
5.8.2.3.6.OpenLink
5.8.2.3.7.Paste
5.8.2.3.8.SelectAll
5.8.2.4.CleartheConsole
5.8.2.5.DisplaySelectedConsole
5.8.2.6.OpenConsole
5.8.2.7.PintheConsole
5.8.2.8.ScrollLock
5.8.3.DebugView
5.8.3.1.ExecutionControlCommands
5.8.3.1.1.Resume
5.8.3.1.2.StepInto
5.8.3.1.3.StepOver
5.8.3.1.4.StepReturn
5.8.3.1.5.Suspend
5.8.3.1.6.Terminate
5.8.3.1.7.Terminate/DisconnectAll
5.8.3.1.8.TerminateandRelaunch
5.8.3.1.9.TerminateandRemove
5.8.3.2.CopyStack
5.8.3.3.Disconnect
5.8.3.4.DroptoFrame
5.8.3.5.EditLaunchConfiguration
5.8.3.6.EditSourceLookup
5.8.3.7.EditStepFilters
5.8.3.8.FilterPackage
5.8.3.9.FilterType
5.8.3.10.Find...
5.8.3.11.LookupSource
5.8.3.12.OpenDeclaredType
5.8.3.13.OpenDeclaredTypeHierarchy
5.8.3.14.Properties
5.8.3.15.Relaunch
5.8.3.16.RemoveAllTerminated
5.8.3.17.ShowMonitors
5.8.3.18.ShowQualifiedNames
5.8.3.19.ShowSystemThreads
5.8.3.20.ShowThreadGroups
5.8.3.21.UseStepFilters
5.8.4.DisplayView
5.8.4.1.Clear
5.8.4.2.ContentAssist
5.8.4.3.CopySelectedStatements
5.8.4.4.CutSelectedStatements
5.8.4.5.Display
5.8.4.6.ExecuteSelectedStatement
5.8.4.7.Find/Replace
5.8.4.8.Inspect
5.8.4.9.Paste
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 4/322
12/10/2015 Javadevelopmentuserguide
5.8.4.10.SelectAll
5.8.5.ExpressionsView
5.8.5.1.DetailPane
5.8.5.1.1.AssignValue
5.8.5.1.2.ContentAssist
5.8.5.1.3.Cut
5.8.5.1.4.Copy
5.8.5.1.5.Display
5.8.5.1.6.Execute
5.8.5.1.7.Find/Replace
5.8.5.1.8.ForceReturn
5.8.5.1.9.Inspect
5.8.5.1.10.MaxLength
5.8.5.1.11.Paste
5.8.5.1.12.SelectAll
5.8.5.1.13.WrapText
5.8.5.2.ViewDisplayCommands
5.8.5.2.1.ShowContants
5.8.5.2.2.ShowLogical
5.8.5.2.3.ShowNull
5.8.5.2.4.ShowQualified
5.8.5.2.5.ShowReferences
5.8.5.2.6.ShowStatic
5.8.5.2.7.ShowTypeNames
5.8.5.3.ViewLayoutCommands
5.8.5.3.1.ShowColumns
5.8.5.3.2.SelectColumns
5.8.5.3.3.HorizontalLayout
5.8.5.3.4.VerticalLayout
5.8.5.3.5.ViewOnly
5.8.5.4.AddWatchExpression
5.8.5.5.AllInstances
5.8.5.6.AllReferences
5.8.5.7.ChangeVariableValue
5.8.5.8.CollapseAll
5.8.5.9.CopyExpressions
5.8.5.10.ConverttoWatchExpression
5.8.5.11.DisableSelectedWatchExpression
5.8.5.12.EditWatchExpression
5.8.5.13.EnableSelectedWatchExpression
5.8.5.14.Find...
5.8.5.15.InspectVariable
5.8.5.16.JavaPreferences
5.8.5.17.ReevaluateWatchExpression
5.8.5.18.RemoveSelectedExpressions
5.8.5.19.RemoveAllExpressions
5.8.5.20.SelectAll
5.8.5.21.ToggleWatchpoint
5.8.6.PackageExplorerview
5.8.6.1.JavaElementFiltersdialog
5.8.7.VariablesView
5.8.7.1.DetailPane
5.8.7.1.1.AssignValue
5.8.7.1.2.ContentAssist
5.8.7.1.3.Cut
5.8.7.1.4.Copy
5.8.7.1.5.Display
5.8.7.1.6.Execute
5.8.7.1.7.Find/Replace
5.8.7.1.8.ForceReturn
5.8.7.1.9.Inspect
5.8.7.1.10.MaxLength
5.8.7.1.11.Paste
5.8.7.1.12.SelectAll
5.8.7.1.13.WrapText
5.8.7.2.ViewDisplayCommands
5.8.7.2.1.ShowContants
5.8.7.2.2.ShowLogical
5.8.7.2.3.ShowNull
5.8.7.2.4.ShowQualified
5.8.7.2.5.ShowReferences
5.8.7.2.6.ShowStatic
5.8.7.2.7.ShowTypeNames
5.8.7.3.ViewLayoutCommands
5.8.7.3.1.ShowColumns
5.8.7.3.2.SelectColumns
5.8.7.3.3.HorizontalLayout
5.8.7.3.4.VerticalLayout
5.8.7.3.5.ViewOnly
5.8.7.4.AllInstances
5.8.7.5.AllReferences
5.8.7.6.ChangeVariableValue
5.8.7.7.CollapseAll
5.8.7.8.CopyVariables
5.8.7.9.CreateWatchExpression
5.8.7.10.Find...
5.8.7.11.InspectVariable
5.8.7.12.JavaPreferences
5.8.7.13.SelectAll
5.8.7.14.ToggleWatchpoint
5.8.8.JavaOutlineView
5.8.9.JavaScrapbookPage
5.8.10.TypeHierarchyView
5.8.11.CallHierarchyView
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 5/322
12/10/2015 Javadevelopmentuserguide
5.8.12.JUnitView
5.8.13.JavadocView
5.9.JavaEditor
5.9.1.JavaContentAssist
5.9.2.JavaFormatter
5.9.3.Quickfix
5.9.4.Quickassist
5.9.5.Suppresswarnings
5.10.WizardsandDialogs
5.10.1.CreateNewElements
5.10.1.1.NewJavaProjectWizard
5.10.1.1.1.JavaBuildPathPage
5.10.1.1.2.AttachingSourcetoJARFilesandVariables
5.10.1.2.NewJavaPackageWizard
5.10.1.3.NewJavaClassWizard
5.10.1.4.NewJavaEnumWizard
5.10.1.5.NewJavaInterfaceWizard
5.10.1.6.NewJavaAnnotationWizard
5.10.1.7.NewSourceFolderWizard
5.10.1.8.NewJavaScrapbookPageWizard
5.10.2.ExportBreakpoints
5.10.3.ExportLaunchConfigurations
5.10.4.ExternalizeStringswizard
5.10.5.ImportBreakpoints
5.10.6.ImportLaunchConfigurations
5.10.7.JARFileExporter
5.10.8.JavadocGeneration
5.10.9.RunnableJARFileExporter
5.10.10.JavaElementFilters
5.10.11.OpenTypeDialog
5.10.12.CreateGetterandSetter
5.10.13.GeneratetoString()
5.10.13.1.FormatTemplates
5.10.13.2.CodeStyles
5.10.13.3.ContentListing
5.10.14.OverrideMethods
5.11.FrequentlyAskedQuestions:JDT
5.12.Glossary
5.13.Icons
5.14.AvailableQuickAssists
5.15.AvailableQuickFixes
5.16.ListofJDTKeyBindings
6.Tipsandtricks
6.1.Editing
6.2.Refactoring
6.3.Searching
6.4.Navigation
6.5.Views
6.6.Miscellaneous
6.7.Debugging
1.Javadevelopmentoverview
TheJDTprojectprovidesthetoolpluginsthatimplementaJavaIDEsupportingthedevelopmentofanyJavaapplication,includingEclipseplugins.ItaddsaJavaprojectnature
andJavaperspectivetotheEclipseWorkbenchaswellasanumberofviews,editors,wizards,builders,andcodemergingandrefactoringtools.TheJDTprojectallowsEclipseto
beadevelopmentenvironmentforitself.
TrytheBasictutorialtogetafirstimpression.DiscovermoreintheTipsandTrickssectionandlearnaboutthelatestfeaturesinWhat'snew.
2.1.Basictutorial
ThistutorialprovidesastepbystepwalkthroughoftheJavadevelopmenttools.
NextSection:Preparingtheworkbench
2.1.1.PreparingEclipse
Inthissection,youwillverifythatEclipseisproperlysetupforJavadevelopment.
Thefollowingisassumed:
YouarestartingwithanewEclipseinstallationwithdefaultsettings.
YouarefamiliarwiththebasicEclipseworkbenchmechanisms,suchasviewsandperspectives.
Ifyou'renotfamiliarwiththebasicworkbenchmechanisms,pleaseseetheGettingStartedchapteroftheWorkbenchUserGuide.
VerifyingJREinstallationandclasspathvariables
1. IfyoustillseetheEclipseWelcomepage,clickthearrowicontobeginusingEclipse.
2. Selectthemenuitem Window>Preferences...toopentheworkbenchpreferences.
3. Selectthe Java>InstalledJREspreferencepagetodisplaytheinstalledJavaRuntimeEnvironments.ConfirmthataJREhasbeendetected.Bydefault,theJREused
toruntheworkbenchwillbeusedtobuildandrunJavaprograms.ItshouldappearwithacheckmarkinthelistofinstalledJREs.WerecommendthatyouuseaJavaSDK
insteadofaJRE.AnSDKisdesignedfordevelopmentandcontainsthesourcecodefortheJavalibrary,easingdebugging.AdditionalSDKscanbeaddedbysearchingthe
harddriveforinstalledSDKs.Todoso,simplyclicktheSearch...buttonandspecifyarootfolderforthesearch.
Ifyouworkwithcodethatdoesnotyetusegenerics(aswedointhistutorial),werecommendthatyouinstallaJavaSDK1.4aswell,butleavethemostrecentversion
checkedasdefault.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 6/322
12/10/2015 Javadevelopmentuserguide
4. Selectthe General>Workspacepreferencepage.ConfirmthattheBuildautomaticallyoptionischecked.
5. Selectthe Java>BuildPathpreferencepage.ConfirmthatSourceandoutputfolderissettoFolders.
6. Selectthe Java>Editorpreferencepage.ConfirmthatoptionReportproblemsasyoutypeischecked.
7. Selectthe Java>Compilerpreferencepage.ConfirmthatoptionCompilercompliancelevelmatchesyourdefaultJREversion(usually1.6).
8. ClickonOKtosavethepreferences.
NextSection:CreatingyourfirstJavaproject
Javaprojects
Classpathvariables
Buildclasspath
WorkingwithJREs
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 7/322
12/10/2015 Javadevelopmentuserguide
InstalledJREsPreferences
JavaEditorPreferences
2.1.2.CreatingyourfirstJavaproject
Inthissection,youwillcreateanewJavaproject.YouwillbeusingJUnitasyourexampleproject.JUnitisanopensourceunittestingframeworkforJava.
GettingtheSampleCode(JUnit)
FirstyouneedtodownloadtheJUnitsourcecode.
1. ClickheretodownloadtheJUnitsourcecode.
2. Savethearchive(donotextract)toadirectoryfromnowonreferencedas<Downloads>.
Creatingtheproject
1. InsideEclipseselectthemenuitemFile>New>Project....toopentheNewProjectwizard
2. SelectJavaProjectthenclickNexttostartthe NewJavaProjectwizard:
Onthispage,
type"JUnit"intheProjectnamefield,and
select"J2SE1.4"intheUseanexecutionenvironmentJREfield.
ThenclickFinish.
3. InthePackageExplorer,expandtheJUnitprojectandselectthesourcefoldersrc.
4. SelectthemenuitemFile>Import....
5. ExpandGeneral,selectArchivefile,andclickNext.
6. ClicktheBrowsebuttonnexttotheArchivefilefieldandbrowsetoselect
<Downloads>/junit381src.jar
Note:Thisstepassumesthatyoufollowedsteps1and2intheGettingtheSampleCodesectionabove.
7. IntheImportwizard,expandtherootnode,pressDeselectAllandselectonlythejunitnode.Youcanexpandandselectelementswithinthejunitdirectoryontheleftpane
toviewtheindividualresourcesthatyouareimportingontherightpane.Note:Donotdeselectanyoftheresourcesinthejunitdirectoryatthistime.Youwillneedallofthese
resourcesinthetutorial.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 8/322
12/10/2015 Javadevelopmentuserguide
8. MakesurethattheJUnitproject'ssourcefolderappearsinthedestinationIntofolderfield.ThenclickFinish.Intheimportprogressindicator,noticethattheimported
resourcesarecompiledastheyareimportedintotheworkbench.ThisisbecausetheBuildautomaticallyoptionischeckedontheWorkbenchpreferencespage.
9. InthePackageExplorerview,expandtheJUnitprojectandthesrcfoldertoviewtheJUnitpackages.
NextSection:BrowsingJavaelementsusingthepackageexplorer
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.1.3.BrowsingJavaelementsusingthepackageexplorer
Inthissection,youwillbrowseJavaelementswithintheJUnitproject.
1. InthePackageExplorerview,makesuretheJUnitprojectandthesourcefolderareexpandedsoyoucanseethepackages.
2. Expandthepackagejunit.frameworktoseetheJavafilescontainedinthepackage.
3. ExpandtheJavafileTestCase.java.NotethatthePackageExplorershowsJavaspecificsubelementsofthesourcecodefile.Thepublictypeanditsmembers(fieldsand
methods)appearinthetree.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 9/322
12/10/2015 Javadevelopmentuserguide
NextSection:OpeningaJavaeditor
Javaviews
PackageExplorerView
2.1.4.1.OpeningaJavaeditor
Inthissection,youwilllearnhowtoopenaneditorforJavafiles.YouwillalsolearnaboutsomeofthebasicJavaeditorfeatures.
1. Expandthepackagejunit.samplesandselectthefileVectorTest.java.YoucanopenVectorTest.javaintheJavaeditorbydoubleclickingonit.Ingeneralyoucanopena
JavaeditorforJavafiles,types,methodsandfieldsbysimplydoubleclickingonthem.Forexample,toopentheeditordirectlyonthemethodtestClonedefinedin
VectorTest.java,expandthefileinthePackageExploreranddoubleclickonthemethod.
2. Noticethesyntaxhighlighting.DifferentkindsofelementsintheJavasourcearerenderedinuniquecolors.ExamplesofJavasourceelementsthatarerendereddifferently
are:
Regularcomments
Javadoccomments
Keywords
Strings
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 10/322
12/10/2015 Javadevelopmentuserguide
3. LookattheOutlineview.ItdisplaysanoutlineoftheJavafileincludingthepackagedeclaration,importdeclarations,fields,typesandmethods.TheOutlineviewusesicons
toannotateJavaelements.Forexample,iconsindicatewhetheraJavaelementisstatic( ),abstract( ),orfinal( ).Differenticonsshowyouwhetheramethodoverridesa
methodfromabaseclass( )orwhenitimplementsamethodfromaninterface( ).
4. ToggletheHideFields,HideStaticMembers,andHideNonPublicMembersbuttonsintheOutlineviewtoolbartofiltertheview'sdisplay.Beforegoingtothenextstep
makesurethattheHideNonPublicMembersandHideStaticFieldsandMethodsbuttonsarenotpressed.
5. IntheOutlineview,selectdifferentelementsandnotethattheyareagaindisplayedinawholefileviewintheeditor.TheOutlineviewselectionnowcontainsarangeindicator
ontheverticalrulerontheleftborderoftheJavaeditorthatindicatestherangeoftheselectedelement.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 11/322
12/10/2015 Javadevelopmentuserguide
NextSection:Usingquickviews
Javaviews
Javaeditor
SortingelementsinJavaviews
JavaOutlineView
JavaEditorPreferences
2.1.4.2.Usingquickviews
Inthissection,youwillbeintroducedtothequickoutlineview.Quickviewsareinplaceviewswhichareshownontopoftheeditorareaandcaneasilybecontrolledusingthe
keyboard.AsecondquickviewwillbeintroducedintheTypeHierarchysection.
QuickOutline
TousethequickoutlineviewintheJavaeditor:
1. Openjunit.samples.VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
2. PressCtrl+OorselectNavigate>QuickOutlineandyouwillseeaninplaceoutlineofthecurrentsourcefile.
3. PressCtrl+Oasecondtimeandallinheritedfields,typesandmethodsareshownaswell(forthetypesmarkedwith ontheleft).Inheritedmembersareshowninblue.
4. Starttypingwhilethequickoutlineviewisshowntofilterthelistofdisplayedelements.Further,usethearrowkeystonavigateintheoutlineviewandpressEntertoreveal
theselectedelementintheJavaeditor.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 12/322
12/10/2015 Javadevelopmentuserguide
5. Clickthetriangleintheupperrightcornertoseethequickviewmenu:
Themenuitemscanbedividedinto3categories:
PositionAllowsyoutoresizeandmovethequickviewandtorememberthesesettings
FilterDefinefilterssothatnotallmembersareshowninthequickoutline.
SortSortthemembersbytheirdefiningtypeoralphabetically.
Note:Ctrl+OalwaysopenstheoutlineforthecurrentJavaeditor.PressCtrl+F3toopenthequickoutlineforthecurrentlyselectedtype.
NextSection:Addingnewmethods
2.1.4.3.Addingnewmethods
1. StartaddingamethodbytypingthefollowingattheendoftheVectorTest.javafile(butbeforetheclosingbraceofthetype)intheJavaeditor:
publicvoidtestSizeIsThree()
Assoonasyoutypethemethodnameintheeditorarea,thenewmethodappearsatthebottomoftheOutlineview.
Inaddition,
errorannotations(redboxes)appearintheoverviewrulerpositionedontherighthandsideoftheeditor,
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 13/322
12/10/2015 Javadevelopmentuserguide
erroriconsappearintheverticalrulerpositionedontheleftoftheeditor,
anerrorindicatorappearsinthetoprightcorneroftheeditor,
errorsaremarkedinthetext.
Theseerrorannotationsindicatethatthecompilationunitiscurrentlynotcorrect.Ifyouhoverovertheerrorinthetext,atooltipappears:Syntaxerrorontoken")",{expected
afterthistoken.Thisiscorrectsincethemethoddoesn'thaveabodyyet.Notethaterrorannotationsintheeditorareupdatedasyoutype.Thisbehaviorcanbecontrolledvia
theReportproblemsasyoutypeoptionlocatedonthe Java>Editorpreferencepage.
2. ClicktheSavebutton.ThecompilationunitiscompiledautomaticallyanderrorsappearinthePackageExplorerview,intheProblemsviewandontheverticalruler(lefthand
sideoftheeditor).InthePackageExplorerview,theerrorsarepropagateduptotheprojectofthecompilationunitcontainingtheerror.
3. Completethenewmethodbytypingthefollowing:
{
//TODO:Checksize
Notethattheclosingcurlybracehasbeeninsertedautomatically.
4. Savethefile.Noticethattheerrorindicatorsdisappearsincethemissingbracehasbeenadded.
NextSection:Usingcontentassist
Javaeditor
JavaEditorPreferences
2.1.4.4.Usingcontentassist
Inthissectionyouwillusecontentassisttofinishwritinganewmethod.Openthefilejunit.samples/VectorTest.javaintheJavaeditorifyoudonotalreadyhaveitopenandselect
thetestSizeIsThree()methodintheOutlineview.Ifthefiledoesn'tcontainsuchamethodseeAddingnewmethodsforinstructionsonhowtoaddthismethod.
1. ReplacetheTODOcommentwiththefollowinglines.
assertTrue(fFull.size()==3)
Vectorv=newVector()
for(inti=0i<3i++)
v.addElement(newObject())
assert
2. Withyourcursorattheendofthewordassert,pressCtrl+Spacetoactivatecontentassist.Thecontentassistwindowwithalistofproposalswillappear.Scrollthelistto
seetheavailablechoices.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 14/322
12/10/2015 Javadevelopmentuserguide
3. Withthecontentassistwindowstillactive,typetheletter't'inthesourcecodeafterassert(withnospaceinbetween).Thelistisnarrowedandonlyshowsentriesstarting
with'assert'.SingleclickvariousitemsinthelisttoviewanyavailableJavadochelpforeachitem.
4. SelectassertTrue(boolean)fromthelistandpressEnter.ThecodefortheassertTrue(boolean)methodisinserted.
5. Completethelinesothatitreadsasfollows:
assertTrue(v.size()==fFull.size())
6. Savethefile.
NextSection:Identifyingproblemsinyourcode
Javaeditor
JavaContentAssist
JavaEditorPreferences
2.1.4.5.Identifyingproblemsinyourcode
Inthissection,youwillreviewthedifferentindicatorsforidentifyingproblemsinyourcode.
BuildproblemsaredisplayedintheProblemsviewandannotatedintheverticalrulerofyoursourcecode.
1. Openjunit.framework/TestCase.javaintheeditorfromthePackageExplorerview.
2. Addasyntaxerrorbydeletingthesemicolonattheendofthepackagedeclarationinthesourcecode.
3. ClicktheSavebutton.Theprojectisrebuiltandtheproblemisindicatedinseveralways:
IntheProblemsview,theproblemsarelisted,
InthePackageExplorerview,theTypeHierarchyortheOutlineview,problemticksappearontheaffectedJavaelementsandtheirparentelements,
Intheeditor'sverticalruler,aproblemmarkerisdisplayedneartheaffectedline,
Squigglylinesappearunderthewordwhichmighthavecausedtheerror,and
Theeditortabisannotatedwithaproblemmarker.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 15/322
12/10/2015 Javadevelopmentuserguide
4. Youcanhoveroverthemarkedwordintheeditortoviewadescriptionoftheproblem.Youcanalsohoverovertheproblemmarkersintheverticaloroverviewrulers.
5. ClicktheClose("X")buttonontheeditor'stabtoclosetheeditor.
6. IntheProblemsview,selectaprobleminthelist.OpenitscontextmenuandselectGoTo.Thefileisopenedintheeditoratthelocationoftheproblem.
7. Correcttheproblemintheeditorbyaddingthesemicolon.ClicktheSavebutton.Theprojectisrebuiltandtheproblemindicatorsdisappear.
8. IntheOutlineview,selectthemethodgetName().Theeditorwillscrolltothismethod.
9. OnthefirstlineofthemethodchangethereturnedvariablefNametofTestName.Whileyoutype,aproblemhighlightunderlineappearsonfTestName,toindicateaproblem.
Hoveringoverthehighlightedproblemwilldisplayadescriptionoftheproblemandapplicablequickfixes.
10. Onthemarkerbaralightbulbmarkerappears.Thelightbulbsignalsthatcorrectionproposalsareavailableforthisproblem.
11. Clicktoplacethecursorontothehighlightederror,andchooseQuickFixfromtheEditmenubar.YoucanalsopressCtrl+1orleftclickthelightbulb.Aselectiondialog
appearswithpossiblecorrections.
12. Select'ChangetofName'tofixtheproblem.Theproblemhighlightlinewilldisappearasthecorrectionisapplied.
13. Closethefilewithoutsaving.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 16/322
12/10/2015 Javadevelopmentuserguide
14. Youcanconfigurehowproblemsareindicatedonthe General>Editors>TextEditors>Annotationspreferencepage.
NextSection:Usingcodetemplates
Javaeditor
Javaviews
Javabuilder
Editorpreferencepage
Quickfix
2.1.4.6.Usingcodetemplates
Inthissectionyouwillusecontentassisttofillinatemplateforacommonloopstructure.Openjunit.samples/VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveit
open.
1. Startaddinganewmethodbytypingthefollowing:
publicvoidtestValues(){
Integer[]expected=newInteger[3]
for
2. Withthecursorattheendoffor,pressCtrl+Spacetoenablecontentassist.Youwillseealistofcommontemplatesfor"for"loops.Whenyousingleclickatemplate,or
selectitwiththeUporDownarrowkeys,you'llseethecodeforthetemplateinitshelpmessage.Notethatthelocalarraynameisguessedautomatically.
3. ChoosetheforiterateoverarrayentryandpressEntertoconfirmthetemplate.Thetemplatewillbeinsertedinyoursourcecode.
4. Nextwechangethenameoftheindexvariablefromitoe.Todososimplypresse,astheindexvariableisautomaticallyselected.Observethatthenameoftheindex
variablechangesatallplaces.Wheninsertingatemplateallreferencestothesamevariableareconnectedtoeachother.Sochangingonechangesalltheothervaluesas
well.
5. Pressingthetabkeymovesthecursortothenextvariableofthecodetemplate.Thisisthearrayexpected.
Sincewedon'twanttochangethename(itwasguessedrightbythetemplate)wepresstabagain,whichleavesthetemplatesincetherearen'tanyvariableslefttoedit.
6. Completetheforloopasfollows:
for(inte=0e<expected.lengthe++){
expected[e]=newInteger(e+1)
}
Integer[]actual=to
7. Withthecursorattheendofto,pressCtrl+Spacetoenablecontentassist.PicktoarrayconvertcollectiontoarrayandpressEntertoconfirmtheselection(or
doubleclicktheselection).
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 17/322
12/10/2015 Javadevelopmentuserguide
Thetemplateisinsertedintheeditorandtypeishighlightedandselected.
8. OverwritetheselectionbytypingInteger.Thetypeofarrayconstructorchangeswhenyouchangetheselection.
9. PressTabtomovetheselectiontocollectionandoverwriteitbytypingfFull.
10. Addasemicolonandthefollowinglinesofcodetocompletethemethod:
assertEquals(expected.length,actual.length)
for(inti=0i<actual.lengthi++)
assertEquals(expected[i],actual[i])
11. Savethefile.
NextSection:Organizingimportstatements
Javaeditor
Templates
TemplatesPreferences
JavaEditorPreferences
2.1.4.7.Organizingimportstatements
Inthissectionyouwillorganizetheimportdeclarationsinyoursourcecode.Openjunit.samples/VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
1. Bydefault,importdeclarationsarehiddenintheOutlineview.SelectViewMenu>Filters...anduncheckImportdeclarations.ClickOKtomakethemvisibleintheOutline
view.
2. DeletetheimportdeclarationsbyselectingthemintheOutlineviewandselectingDeletefromthecontextmenu.ConfirmtheresultingdialogwithYes.Youwillseenumerous
compilewarningsintheverticalrulersincethetypesusedinthemethodarenolongerimported.
3. Fromthecontextmenuintheeditor,selectSource>OrganizeImports.Therequiredimportstatementsareaddedtothebeginningofyourcodebelowthepackage
declaration.
YoucanalsochooseOrganizeImportsfromthecontextmenuoftheimportdeclarationsintheOutlineview.
Note:Youcanspecifytheorderoftheimportdeclarationsusingthe Java>CodeStyle>OrganizeImportspreferencepage.
4. Savethefile.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 18/322
12/10/2015 Javadevelopmentuserguide
NextSection:Usingthelocalhistory
Javaeditor
OrganizeImportsPreferences
2.1.4.8.Usingthelocalhistory
Inthissection,youwillusethelocalhistoryfeaturetoswitchtoapreviouslysavedversionofanindividualJavaelement.
1. Openjunit.samples/VectorTest.javafileintheJavaeditorandselectthemethodtestCapacity()intheOutlineview.
2. Changethecontentofthemethodsothatthe'for'statementsreadsas:
for(inti=0i<99i++)
SavethefilebypressingCtrl+S.
3. IntheOutlineview,selectthemethodtestCapacity(),andfromitscontextmenu,selectReplaceWith>ElementfromLocalHistory.
4. IntheReplaceJavaElementfromLocalHistorydialog,theLocalHistorylistshowsthevarioussavedstatesofthemethod.TheJavaSourceComparepaneshowsdetails
ofthedifferencesbetweentheselectedhistoryresourceandtheexistingworkbenchresource.
5. Inthetoppane,selectthepreviousversion,andclicktheReplacebutton.IntheJavaeditor,themethodisreplacedwiththeselectedhistoryversion.
6. Savethefile.
7. Besidereplacingamethod'sversionwithapreviousoneyoucanalsorestoreJavaelementsthatweredeleted.Again,selectthemethodtestCapacity()intheOutlineview,
andfromitscontextmenu,selectDelete.ConfirmtheresultingdialogwithYesandsavethefile.
8. NowselectthetypeVectorTestintheOutlineview,andfromitscontextmenu,selectRestorefromLocalHistory....SelectandcheckthemethodtestCapacity()inthe
AvailableJavaElementspane.Asbefore,theLocalHistorypaneshowstheversionssavedinthelocalhistory.
9. IntheLocalHistorypane,selecttheearlierworkingversionandthenclickRestore.
NextSection:Extractinganewmethod
Javaeditor
Usingthelocalhistory
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 19/322
12/10/2015 Javadevelopmentuserguide
2.1.4.9.Extractinganewmethod
Inthissection,youwillimprovethecodeoftheconstructorofjunit.framework.TestSuite.Tomaketheintentofthecodeclearer,youwillextractthecodethatcollectstestcases
frombaseclassesintoanewmethodcalledcollectInheritedTests.
1. Inthejunit.framework/TestSuite.javafile,selectthefollowingrangeofcodeinsidetheTestSuite(Class)constructor:
ClasssuperClass=theClass
Vectornames=newVector()
while(Test.class.isAssignableFrom(superClass)){
Method[]methods=superClass.getDeclaredMethods()
for(inti=0i<methods.lengthi++){
addTestMethod(methods[i],names,theClass)
}
superClass=superClass.getSuperclass()
}
2. Fromtheselection'scontextmenuintheeditor,selectRefactor>ExtractMethod....
3. IntheMethodNamefield,typecollectInheritedTests.
4. Topreviewthechanges,pressPreview>.Thepreviewpagedisplaysthechangesthatwillbemade.PressOKtoextractthemethod.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 20/322
12/10/2015 Javadevelopmentuserguide
5. GototheextractedmethodbyselectingitintheOutlineview.
NextSection:CreatingaJavaclass
Javaeditor
Refactoringsupport
JavaPreferences
2.1.5.CreatingaJavaclass
Inthissection,youwillcreateanewJavaclassandaddmethodsusingcodegenerationactions.
1. InthePackageExplorerview,selecttheJUnitproject.ClicktheNewJavaPackagebuttoninthetoolbar,orselectNew>Packagefromtheproject'scontextmenu.
2. IntheNamefield,typetestasthenameforthenewpackage.ThenclickFinish.
3. InthePackageExplorerview,selectthenewtestpackageandclicktheNewJavaClassbuttoninthetoolbar.
4. MakesurethatJUnitappearsintheSourceFolderfieldandthattestappearsinthePackagefield.IntheNamefield,typeMyTestCase.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 21/322
12/10/2015 Javadevelopmentuserguide
5. ClicktheBrowsebuttonnexttotheSuperclassfield.
6. IntheChooseatypefieldintheSuperclassSelectiondialog,typeTesttonarrowthelistofavailablesuperclasses.
7. SelecttheTestCaseclassandclickOK.
8. SelectthecheckboxforConstructorsfromsuperclass.
9. ClickFinishtocreatethenewclass.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 22/322
12/10/2015 Javadevelopmentuserguide
10. Thenewfileisopenedintheeditor.Itcontainsthenewclass,theconstructorandcomments.Youcanselectoptionsforthecreationandconfigurationofgenerated
commentsinthe Java>CodeStyle>CodeTemplatespreferencepage.
11. IntheOutlineviewselectthenewclassMyTestCase.OpenthecontextmenuandselectSource>Override/ImplementMethods....
12. IntheOverrideMethodsdialog,checksetUp()andtearDown()andclickOK.Twomethodsareaddedtotheclass.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 23/322
12/10/2015 Javadevelopmentuserguide
13. ChangethebodyofsetUp()tocontainer=newVector()
14. containerandVectorareunderlinedwithaproblemhighlightlineastheycannotberesolved.Alightbulbappearsonthemarkerbar.Movethemouseovertheunderlinedword
Vector.Ahoverappearsthatshowstheerrormessageandcontainsquickfixes.MovethemouseintothehoverandclickImport'Vector'(java.util).Thisaddsthemissing
importdeclaration.
Theblinkingcursorshouldstillbeonthelinethatcontainstheerror(ifnot,setittotheendoftheline).PressCtrl+1.Thisletsthecursorjumptothenearesterrorlocation
andopensthequickfixproposals.ChooseCreatefield'container'toaddthenewfield.
15. IntheOutlineview,selecttheclassMyTestCase.OpenthecontextmenuandselectSource>GenerateGettersandSetters....
16. TheGenerateGetterandSetterdialogsuggeststhatyoucreatethemethodsgetContainerandsetContainer.SelectbothandclickOK.Agetterandsettermethodforthefield
containerareadded.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 24/322
12/10/2015 Javadevelopmentuserguide
17. Savethefile.
18. Theformattingofgeneratedcodecanbeconfiguredinthe Java>CodeStyle>Formatterpreferencepage.Ifyouuseaprefixorsuffixforfieldnames(e.g.fContainer),
youcanspecifythisinthe Java>CodeStylepreferencepagesothatgeneratedgettersandsetterswillsuggestmethodnameswithouttheprefixorsuffix.
NextSection:RenamingJavaelements
Javaviews
Javaeditor
NewJavaClasswizard
Sourceactions
Quickfix
Overridemethodsdialog
GenerateGetterandSetterdialog
Codeformatterpreferencepage
Codestylepreferencepage
Codetemplatespreferencepage
2.1.6.RenamingJavaelements
Inthissection,youwillrenameaJavaelementusingrefactoring.Refactoringactionschangethestructureofyourcodewithoutchangingitssemantics(behavior).
1. InthePackageExplorerview,selectjunit.framework/TestCase.java.
2. Fromitscontextmenu,selectRefactor>Rename.
3. IntheNewNamefieldontheRenameCompilationUnitpage,type"TestCase2".
4. Topreviewthechangesthatwillbemadeasaresultofrenamingtheclass,pressNext.
5. Theworkbenchanalyzestheproposedchangeandpresentsyouwithapreviewofthechangesthatwouldtakeplaceifyourenamethisresource.
Sincerenamingacompilationunitwillaffecttheimportstatementsinothercompilationunits,thereareothercompilationunitsaffectedbythechange.Theseareshownina
listofchangesinthepreviewpane.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 25/322
12/10/2015 Javadevelopmentuserguide
6. OntheRefactoringpreviewpage,youcanscrollthroughtheproposedchangesandselectordeselectchanges,ifnecessary.Youwilltypicallyacceptalloftheproposed
changes.
7. ClickFinishtoacceptallproposedchanges.
Youhaveseenthatarefactoringactioncancausemanychangesindifferentcompilationunits.Thesechangescanbeundoneasagroup.
1. Inthemenubar,selectEdit>UndoRenameCompilationUnit.
2. Therefactoringchangesareundone,andtheworkbenchreturnstoitspreviousstate.Youcanundorefactoringactionsrightupuntilyouchangeandsaveacompilationunit,at
whichtimetherefactoringundobufferiscleared.
NextSection:MovingandcopyingJavaelements
Refactoringsupport
Refactoringactions
Refactoringwizard
Javapreferences
2.1.7.MovingandcopyingJavaelements
Inthissection,youwilluserefactoringtomovearesourcebetweenJavapackages.Refactoringactionschangethestructureofyourcodewithoutchangingitssemanticbehavior.
1. InthePackageExplorerview,selecttheMyTestCase.javafilefromthetestpackageanddragitintothejunit.samplespackage.Dragginganddroppingthefileissimilarto
selectingthefileandchoosingRefactor>Movefromthecontextmenu.
2. Youwillbepromptedtoselectwhetherornottoupdatereferencestothefileyouaremoving.Typically,youwillwanttodothistoavoidcompileerrors.Youcanpressthe
Previewbuttontoseethelistofchangesthatwillbemadeasaresultofthemove.
3. PressOK.Thefileismoved,anditspackagedeclarationchangestoreflectthenewlocation.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 26/322
12/10/2015 Javadevelopmentuserguide
4. UseEdit>UndoMovetoundothemove.
Thecontextmenuisanalternativetousingdraganddrop.Whenusingthemenu,youmustspecifyatargetpackageintheMovedialog,inadditiontoselectingtheupdate
referencesoptionsyou'vealreadyseen.
1. SelecttheMyTestCase.javafileandfromitscontextmenu,selectRefactor>Move.
2. IntheMovedialog,expandthehierarchytobrowsethepossiblenewlocationsfortheresource.Selectthejunit.samplespackage,thenclickOK.Theclassismoved,andits
packagedeclarationisupdatedtothenewlocation.
NextSection:NavigatetoaJavaelement'sdeclaration
Javaviews
Refactoringsupport
Refactoringactions
Refactoringwizard
Javapreferences
2.1.8.NavigatetoaJavaelement'sdeclaration
Inthissection,youwilllearnhowtoopenatypeintheJavaEditorandhowtonavigatetorelatedtypesandmembers.
1. OpentheOpenTypedialogbypressingCtrl+Shift+T,choosingNavigate>OpenType...,orclickingthetoolbaricon( ).TypeMoney,presstheArrowDownkeyafew
timestoselectMoneyTest,andthenpressEntertoopenthetypeintheJavaeditor.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 27/322
12/10/2015 Javadevelopmentuserguide
2. OnthefirstlineoftheMoneyTestclassdeclaration,selectthesuperclassTestCaseandeither
fromthemenubarselectNavigate>OpenDeclarationor
pressF3.
TheTestCaseclassopensintheeditorareaandisalsorepresentedintheOutlineview.
Note:Thiscommandalsoworksonmethodsandfields.
3. WiththeTestCase.javaeditoropenandtheclassdeclarationselected:
fromthemenubarselectNavigate>OpenTypeHierarchyor
pressF4.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 28/322
12/10/2015 Javadevelopmentuserguide
4. TheTypeHierarchyviewopenswiththeTestCaseclassdisplayed.
Note:YoucanalsoopeneditorsontypesandmethodsintheTypeHierarchyview.
NextSection:Viewingthetypehierarchy
Openinganeditorforaselectedelement
TypeHierarchyView
2.1.9.Viewingthetypehierarchy
Inthissection,youwilllearnaboutusingtheTypeHierarchyviewbyviewingclassesandmembersinavarietyofdifferentways.
1. InthePackageExplorerview,findjunit.framework/TestCase.java.Fromitscontextmenu,select OpenTypeHierarchy.Youcanalsoopentypehierarchyview:
fromthemenubarbyselectingNavigate>OpenTypeHierarchy.
fromthekeyboardbypressingF4afterselectingTestCase.java.
2. Thebuttonsintheviewtoolbarcontrolwhichpartofthehierarchyisshown.ClicktheShowtheTypeHierarchybuttontoseetheclasshierarchy,includingthebase
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 29/322
12/10/2015 Javadevelopmentuserguide
classesandsubclasses.ThesmallarrowontheleftsideofthetypeiconofTestCaseindicatesthatthehierarchywasopenedonthistype.
3. ClicktheShowtheSupertypeHierarchybuttontoseeahierarchyshowingthetype'sparentelementsincludingimplementedinterfaces.Thisviewshowstheresultsof
goingupthetypehierarchy.
Inthis"reversedhierarchy"view,youcanseethatTestCaseimplementstheTestinterface.
4. ClicktheShowtheSubtypeHierarchybuttonintheviewtoolbar.
5. ClicktheLockViewandShowMembersinHierarchybuttoninthetoolbarofthememberpane,thenselecttherunTest()methodinthememberpane.Theviewwillnow
showallthetypesimplementingrunTest().
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 30/322
12/10/2015 Javadevelopmentuserguide
6. IntheTypeHierarchyview,clicktheShowtheSupertypeHierarchybutton.Thenonthememberpane,selectcountTestCases()todisplaytheplaceswherethismethodis
declared.
7. IntheTypeHierarchyviewselecttheTestelementandselectFocusOn'Test'fromitscontextmenu.TestispresentedintheTypeHierarchyview.
8. ActivatethePackageExplorerviewandselectthepackagejunit.framework.UseOpenTypeHierarchyfromitscontextmenu.Ahierarchyisopenedcontainingallclassesof
thepackage.Forcompletionofthetree,thehierarchyalsoshowssomeclassesfromotherpackages.Thesetypesareshownbyatypeiconwithawhitefill.
9. UsePreviousTypeHierarchiestogobacktoapreviouslyopenedelement.Clickonthearrownexttothebuttontoseealistofelementsorclickonthebuttontoeditthe
historylist.
IfyouareworkingintheeditorandonlywanttodoaquicklookupforahierarchyyoucanusetheQuickTypeHierarchy:
1. Openjunit.framework.TestCase.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
2. SelectthetypenameintheJavaeditor
3. PressCtrl+TorinvokeNavigate>QuickTypeHierarchyandtheinplacetypehierarchyviewisshown.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 31/322
12/10/2015 Javadevelopmentuserguide
4. PressingCtrl+Twhilethetypehierarchyviewisshownwilltogglebetweensupertypehierarchyandsubtypehierarchy.
Toseewhereavirtualmethodcallcanresolveto:
1. InthebodyofrunBare()selecttheinvocationofsetUp()
2. PressCtrl+TorinvokeNavigate>QuickTypeHierarchyandtheinplacetypehierarchyviewisshown.
3. YoucanseethatsetUp()isimplementedin3moreclasses.ObjectandAssertareonlyshownwithawhitefilledimagesasareonlyrequiredtocompletethehierarchybutdo
notimplementsetUp()
4. SelectatypetonavigatetoitsimplementationofsetUp()
NextSection:Searchingtheworkbench
Javaviews
TypeHierarchyview
JavaBasepreferencepage
2.1.10.Searchingtheworkbench
Inthissection,youwillsearchtheworkbenchforJavaelements.
IntheSearchdialog,youcanperformfile,textorJavasearches.Javasearchesoperateonthestructureofthecode.Filesearchesoperateonthefilesbynameand/ortextcontent.
Javasearchesarefaster,sincethereisanunderlyingindexingstructureforthecodestructure.Textsearchesallowyoutofindmatchesinsidecommentsandstrings.
PerformingaJavasearchfromtheworkbench
1. IntheJavaperspective,clicktheSearch( )buttonintheworkbenchtoolbaroruseSearch>Java...fromthemenubar.
2. Ifitisnotalreadyselected,selecttheJavaSearchtab.
3. IntheSearchstringfield,typerunTest.IntheSearchForarea,selectMethod,andintheLimitToarea,selectReferences.
VerifythattheScopeissettoWorkspace.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 32/322
12/10/2015 Javadevelopmentuserguide
ThenclickSearch.WhilesearchingyoumayclickCancelatanytimetostopthesearch.Partialresultswillbeshown.
4. IntheJavaperspective,theSearchviewshowsthesearchresults.
SearchingfromaJavaview
Javasearchescanalsobeperformedfromspecificviews,includingtheOutline,TypeHierarchyviewandthePackageExplorerview.
1. InthePackageExplorerview,doubleclickjunit.framework.Assert.javatoopenitinaneditor.
2. IntheOutlineview,selectthefail(String)method,andfromitscontextmenu,selectReferences>Workspace.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 33/322
12/10/2015 Javadevelopmentuserguide
Searchingfromaneditor
FromthePackageExplorerview,openjunit.framework.TestCase.java.Intheeditor,selecttheclassnameTestCaseandfromthecontextmenu,selectReferences>Workspace.
Continuingasearchfromthesearchview
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 34/322
12/10/2015 Javadevelopmentuserguide
TheSearchResultsviewshowstheresultsfortheTestCasesearch.Selectasearchresultandopenthecontextmenu.Youcancontinuesearchingtheselectedelement's
referencesanddeclarations.
Ifyouwanttofollowmultiplelevelsofmethodcalls,youcanalsouseNavigate>OpenCallHierarchy.
Performingafilesearch
1. IntheJavaperspective,clicktheSearchbuttonintheworkbenchtoolbarorselectSearch>Filefromthemenubar.
2. Ifitisnotalreadyselected,selecttheFileSearchtab.
3. IntheContainingtextfield,typeTestCase.MakesurethattheFilenamepatternsfieldissetto*.java.TheScopeshouldbesettoWorkspace.ThenclickSearch.
4. Tofindallfilesofagivenfilenamepattern,leavetheContainingTextfieldempty.
Viewingprevioussearchresults
IntheSearchResultsview,clickthearrownexttothePreviousSearchResultstoolbarbuttontoseeamenucontainingthelistofthemostrecentsearches.Youcanchooseitems
fromthismenutoviewprevioussearches.ThelistcanbeclearedbychoosingClearHistory.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 35/322
12/10/2015 Javadevelopmentuserguide
ThePreviousSearchResultsbuttonwilldisplayadialogwiththelistofallprevioussearchesfromthecurrentsession.
Selectingaprevioussearchfromthisdialogwillletyouviewthatsearch.
NextSection:Runningyourprograms
Javasearch
Refactoringactions
Refactoringwizard
Javapreferences
2.1.11.Runningyourprograms
Inthissection,youwilllearnmoreaboutrunningJavaprogramsintheworkbench.
1. InthePackageExplorerview,findjunit.textui/TestRunner.javaanddoubleclickittoopenitinaneditor.
2. IntheOutlineview,noticethattheTestRunnerclasshasaniconwhichindicatesthattheclassdefinesamainmethod.
3. RightclickonTestRunner.javainthePackageExplorerandselectRunAs>JavaApplication.ThiswilllaunchtheselectedclassasalocalJavaapplication.TheRunAs
contextmenuitemisalsoavailableinotherplaces,suchastheOutlineview.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 36/322
12/10/2015 Javadevelopmentuserguide
4. NoticethattheprogramhasfinishedrunningandthefollowingmessageappearsintheConsoleviewtellingyouthattheprogramneedsanexecutionargument.Running
classfromthePackageExplorerasaJavaApplicationusesthedefaultsettingsforlaunchingtheselectedclassanddoesnotallowyoutospecifyanyarguments.
5. Tospecifyarguments,usethedropdownRunmenuinthetoolbarandselectRunConfigurations....
YoucanalsoCtrl+Clickaconfigurationinthedropdownmenutostarteditingthatconfiguration.
6. Thistime,theLaunchConfigurationsdialogopenswiththeTestRunnerlaunchconfigurationselected.Alaunchconfigurationallowsyoutoconfigurehowaprogramis
launched,includingitsarguments,classpath,andotheroptions.(AdefaultlaunchconfigurationwascreatedforyouwhenyouchoseRun>JavaApplication).
7. SelecttheArgumentstabandtypejunit.samples.VectorTestintheProgramargumentsarea.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 37/322
12/10/2015 Javadevelopmentuserguide
8. ClickRun.Thistimetheprogramrunscorrectly,indicatingthenumberofteststhatwererun.
9. SwitchtotheDebugperspective.IntheDebugview,noticethataprocessforthelastprogramlaunchwasregisteredwhentheprogramwasrun.
Bydefault,theDebugviewautomaticallyremovesanyterminatedlauncheswhenanewlaunchiscreated.Thispreferencecanbeconfiguredonthe Run/Debug>
Launchingpreferencepage
Note:YoucanrelaunchaterminatedprocessbyselectingRelaunchfromitscontextmenu.
10. SelectthedropdownmenufromtheRunbuttonintheworkbenchtoolbar.Thislistcontainsthepreviouslylaunchedprograms.Theseprogramscanberelaunchedby
selectingtheminthehistorylist.
11. Bydefaultthecurrentlyselectedresourceoractiveeditorislaunchedwhentherunbuttonishit.Ifnoneoftheseislaunchablethecurrentprojectwillbelaunched.Youcan
configurethisbehaviorunder Run/Debug>Launching.
12. FromthecontextmenuintheDebugview(ortheequivalenttoolbarbutton),selectRemoveAllTerminatedtocleartheviewofterminatedlaunchprocesses.
NextSection:Debuggingyourprograms
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Runninganddebugging
Debugview
Runmenuactions
Runanddebugtoolbaractions
2.1.12.Debuggingyourprograms
Inthissection,youwilldebugaJavaprogram.
1. InthePackageExplorerviewintheJavaperspective,doubleclickjunit.samples/VectorTest.javatoopenitinaneditor.
2. PlaceyourcursorontheverticalruleralongtheleftedgeoftheeditorareaonthefollowinglineinthesetUp()method:
fFull.addElement(newInteger(1))
anddoubleclickontherulertosetabreakpoint.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 38/322
12/10/2015 Javadevelopmentuserguide
Thebreakpointiconindicatesthestatusofthebreakpoint.Theplainbluebreakpointiconindicatesthatthebreakpointhasbeenset,butnotyetinstalled.
Note:OncetheclassisloadedbytheJavaVM,thebreakpointwillbeinstalledandacheckmarkoverlaywillbedisplayedonthebreakpointicon.
3. InthePackageExplorerview,selectthejunit.samplespackageandselectDebugAs,andthenJavaApplication.Whenyourunaprogramfromapackage,youwillbe
promptedtochooseatypefromallclassesinthepackagethatdefineamainmethod.
4. SelecttheVectorTestiteminthedialog,thenclickOK.
Note:Youcanalsosimplyhitthedebugbutton whichwilllaunchthecurrentlyselectedresourceoractiveeditor.SelectJavaApplicationwhenyouare
promptedtoselectawaytodebugVectorTest.
5. Theprogramwillrununtilthebreakpointisreached.Whenthebreakpointishit,executionissuspended,andyouareaskedwhethertoopentheDebugperspective.Click
Yes.Noticethattheprocessisstillactive(notterminated)intheDebugview.Otherthreadsmightstillberunning.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 39/322
12/10/2015 Javadevelopmentuserguide
Note:Thebreakpointnowhasacheckmarkoverlay sincetheclassVectorTestwasloadedintheJavaVM.
6. IntheeditorintheDebugperspective,selectnewVector()fromthelineabovewherethebreakpointisset,andfromitscontextmenu,selectInspect.
7. Theexpressionisevaluatedinthecontextofthecurrentstackframe,andapopupappearswhichdisplaystheresults.YoucansendaresulttotheExpressionsviewby
pressingthekeybindingdisplayedinthepopup.
8. Expressionsthatyouevaluatewhiledebuggingaprogramwillbelistedinthisview.Todeleteanexpressionafterworkingwithit,selecttheexpressionandchooseRemove
fromitscontextmenu.
9. TheVariablesview(availableonatabalongwiththeExpressionsview)displaysthevaluesofthevariablesintheselectedstackframe.Expandthethis.fFulltreeinthe
VariablesviewuntilyoucanseeelementCount.
10. Thevariables(e.g.,elementCount)intheVariablesviewwillchangewhenyoustepthroughVectorTestintheDebugview.Tostepthroughthecode,clicktheStepOver( )
button.Executionwillcontinueatthenextlineinthesamemethod(or,ifyouareattheendofamethod,itwillcontinueinthemethodfromwhichthecurrentmethodwas
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 40/322
12/10/2015 Javadevelopmentuserguide
called).
11. Inthevariablesviewyoucanchoosetoseecertaintypesaslogicalstructures.Thishidestheimplementationdetailsofatypeandsimplyshowsitasarraysorfields.You
candefinelogicalstructuresbyyourselfinthepreferencepageJava>Debug>LogicalStructures.
Breakpoints
Remotedebugging
Localdebugging
Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads
Debugpreferences
Debugview
Runmenuactions
Runanddebugtoolbaractions
Breakpointsview
Consoleview
Displayview
Expressionsview
Variablesview
2.1.13.Evaluatingexpressions
Inthissection,youwillevaluateexpressionsinthecontextofyourrunningJavaprogram.
1. Debugjunit.samples.VectorTest.javatothebreakpointinthesetUp()methodandselectStepOvertwicetopopulatefFull.(SeetheDebuggingyourProgramssectionfor
fulldetails.)
2. OpentheDisplayviewbyselectingWindow>ShowView>Displayandtypethefollowinglineintheview:
fFull.size()
3. Selectthetextyoujusttyped,andfromitscontextmenu,selectDisplay.(YoucanalsochooseDisplayResultofEvaluatingSelectedText( )fromtheDisplayview
toolbar.)
4. TheexpressionisevaluatedandtheresultisdisplayedintheDisplayview.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 41/322
12/10/2015 Javadevelopmentuserguide
5. OnanewlineintheDisplayview,typethefollowingline:
fFull.toArray()
6. Selectthisline,andselectInspectfromthecontextmenu.(YoucanalsochooseInspectResultofEvaluatingSelectedText( )fromtheDisplayviewtoolbar.)
7. Alightweightwindowopenswiththevalueoftheevaluatedexpression.
NextSection:Evaluatingsnippets
Debugger
Evaluatingexpressions
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Expressionsview
2.1.14.Evaluatingsnippets
Inthissection,youwillevaluateJavaexpressionsusingtheJavascrapbook.JavascrapbookpagesallowyoutoexperimentwithJavacodefragmentsbeforeputtingtheminyour
program.
1. IntheFilemenuselectNew>Other>Java>JavaRun/Debug>ScrapbookPage.Youwillbepromptedforafolderdestinationforthepage.
2. IntheEnterorselectthefolderfield,typeorbrowsebelowtoselecttheJUnitprojectrootdirectory.
3. IntheFilenamefield,typeMyScrap.
4. ClickFinishwhenyouaredone.Ascrapbookpageresourceiscreatedforyouwiththejpagefileextension.(Thejpagefileextensionwillbeaddedautomaticallyifyoudo
notenterityourself.)Thescrapbookpageopensautomaticallyinaneditor.
5. Intheeditor,typeSystem.getandthenusecontentassist(Ctrl+Space)tocompletethesnippetasSystem.getProperties().
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 42/322
12/10/2015 Javadevelopmentuserguide
6. SelecttheentirelineyoujusttypedandselectDisplayfromthecontextmenu.YoucanalsoselectDisplayResultofEvaluatingSelectedTextfromthetoolbar.
7. Whentheevaluationcompletes,theresultoftheevaluationisdisplayedandhighlightedinthescrapbookpage.
8. YoucaninspecttheresultofanevaluationbyselectingtextandchoosingInspectfromthecontextmenu(orselectingInspectResultofEvaluatingSelectedTextfromthe
toolbar.)
9. Whenyouarefinishedevaluatingcodesnippetsinthescrapbookpage,youcanclosetheeditor.Savethechangesinthepageifyouwanttokeepthesnippetsforfuture
use.
NextSection:UsingtheJavabrowsingperspective
Debugger
CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
NewJavaScrapbookPagewizard
Javascrapbookpage
Expressionsview
2.1.15.UsingtheJavabrowsingperspective
InthissectionyouwillusetheJavabrowsingperspectivetobrowseandmanipulateyourcode.BrowsingJavaelementswiththePackageExplorergivesanoverviewofusingthe
PackageExplorertobrowseelements.IncontrasttothePackageExplorer,whichorganizesallJavaelementsinatree,consistingofprojects,packages,compilationunits,types,
etc.,thebrowsingperspectiveusesdistinctviewstopresentthesameinformation.Selectinganelementinoneview,willshowitscontentinanotherview.
Toopenabrowsingperspectiveactivate Window>OpenPerspective>JavaBrowsingfromwithintheJavaperspectiveorusethecontextmenuoftheOpenaPerspective
toolbarbutton.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 43/322
12/10/2015 Javadevelopmentuserguide
Theviewsoftheperspectiveareconnectedtoeachotherinthefollowingways:
SelectinganelementintheProjectsviewsshowsitspackagesinthePackagesview.
TheTypesviewshowsthetypescontainedinthepackageselectedinthePackagesview.
TheMembersviewshowsthemembersofaselectedtype.Functionally,theMembersviewiscomparabletotheOutlineviewusedinthenormalJavaperspective.
SelectinganelementintheMembersviewrevealstheelementintheeditor.Ifthereisn'taneditoropenfortheelement,doubleclickingontheelementwillopena
correspondingeditor.
Allfourviewsarebydefaultlinkedtotheactiveeditor.Thismeansthattheviewswilladjusttheircontentandtheirselectionaccordingtothefilepresentedintheactiveeditor.The
followingstepsillustratethisbehavior:
1. Selectjunit.extensionsinthePackagesview.
2. OpentypeTestSetupintheeditorbydoubleclickingitintheTypesview.
3. NowgivebackfocustotheeditoropenedonfileTestCase.javabyclickingontheeditortab.ThePackages,TypesandMembersviewadjusttheircontentandselectionsto
reflecttheactiveeditor.ThePackagesview'sselectionissettojunit.frameworkandtheTypesviewshowsthecontentofthejunit.frameworkpackages.Inaddition,thetype
TestCaseisselected.
Functionally,theJavabrowsingperspectiveisfullycomparabletotheJavaperspective.Thecontextmenusforprojects,packages,types,etc.andtheglobalmenuandtoolbarare
thesame.ThereforeactivatingthesefunctionsisanalogoustoactivatingthemintheJavaperspective.
NextSection:WritingandrunningJUnittests
2.1.16.WritingandrunningJUnittests
Inthissection,youwillbeusingtheJUnittestingframeworktowriteandruntests.TogetstartedwithJUnityoucanrefertotheJUnitCookbook.
WritingTests
Createaproject"JUnitTest".Nowyoucanwriteyourfirsttest.YouimplementthetestinasubclassofTestCase.YoucandosoeitherusingthestandardClasswizardorthe
specializedTestCasewizard:
1. OpentheNewwizard(File>New>JUnitTestCase).
2. SelectNewJUnit3testandenter"TestFailure"asthenameofyourtestclass:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 44/322
12/10/2015 Javadevelopmentuserguide
Note:IfyouwanttouseJUnit4testsyouhavetomakesurethatyourcompilercomplianceissetto1.5.
3. Youwillseeawarningmessageaskingyoutoaddthejunitlibrarytothebuildpath.UsetheClickherelinktoaddthejunitlibraryautomatically.
4. ClickFinishtocreatethetestclass.
AddatestmethodthatfailstotheclassTestFailure.Aquickwaytoenteratestmethodiswiththetesttemplate.Todoso,placethecursorinsidetheclassdeclaration.Type"test"
followedbyCtrl+Spacetoactivatecodeassistandselectthe"test"template.ChangethenameofthecreatedmethodtotestFailureandinvokethefail()method.
publicvoidtestFailure()throwsException{
fail()
}
Nowyouarereadytorunyourfirsttest.
RunningTests
TorunTestFailurehittherunbuttoninthetoolbar.ItwillautomaticallyrunasJUnitTest.YoucaninspectthetestresultsintheJUnitview.Thisviewshowsyouthetestrun
progressandstatus:
Theviewisshowninthecurrentperspectivewheneveryoustartatestrun.AconvenientarrangementfortheJUnitviewistodockitasafastview.TheJUnitviewhastwotabs:
oneshowsyoualistoffailuresandtheothershowsyouthefulltestsuiteasatree.Youcannavigatefromafailuretothecorrespondingsourcebydoubleclickingthecorresponding
lineinthefailuretrace.
DocktheJUnitviewasafastview,removethefail()statementinthemethodtestFailure()sothatthetestpassesandrerunthetestagain.Youcanrerunatesteitherbyclickingthe
Rerunbuttonintheview'stoolbaroryoucanreruntheprogramthatwaslastlaunchedbyactivatingtheRundropdown.Thistimethetestshouldsucceed.Becausethetestwas
successful,theJUnitviewdoesn'tpopup,butthesuccessindicatorshowsontheJUnitviewiconandthestatuslineshowsthetestresult.Asaremindertorerunyourteststhe
viewiconisdecoratedbya"*"wheneveryouchangetheworkspacecontentsaftertherun.
Asuccessfultestrun
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 45/322
12/10/2015 Javadevelopmentuserguide
Asuccessfultestrun,buttheworkspacecontentshavechangedsincethelasttestrun.
Inadditiontorunningatestcaseasdescribedaboveyoucanalso:
Runalltestsinsideaproject,sourcefolder,orpackage
Selectaproject,packageorsourcefolderandrunalltheincludedtestswithRunas>JUnitTest.Thiscommandfindsalltestsinsideaproject,sourcefolderorpackageand
executesthem.
Runasingletestmethod
SelectatestmethodintheOutlineorPackageExplorerandwithRunas>JUnitTesttheselectedtestmethodwillberun.
Rerunasingletest
SelectatestintheJUnitviewandexecuteRunfromthecontextmenu.
CustomizingaTestConfiguration
WhenyouwanttopassparametersorcustomizethesettingsforatestrunyouopentheLaunchConfigurationDialog.SelectOpenRunDialog....intheRundropdownmenuinthe
toolbar:
Inthisdialogyoucanspecifythetesttoberun,itsarguments,itsruntimeclasspath,andtheJavaruntimeenvironment.
DebuggingaTestFailure
Inthecaseofatestfailureyoucanfollowthesestepstodebugit:
1. DoubleclickthefailureentryfromtheFailurestabintheJUnitviewtoopenthecorrespondingfileintheeditor.
2. Setabreakpointatthebeginningofthetestmethod.
3. SelectthetestcaseandexecuteDebugAs>JUnitTestfromtheDebugdropdown.
AJUnitlaunchconfigurationhasa"keepalive"option.IfyourJavavirtualmachinesupports"hotcodereplacement"youcanfixthecodeandrerunthetestwithoutrestartingthefull
testrun.ToenablethisoptionselecttheKeepJUnitrunningafteratestrunwhendebuggingcheckboxintheJUnitlaunchconfiguration.
CreatingaTestSuite
TheJUnitTestSuitewizardhelpsyouwiththecreationofatestsuite.Youcanselectthesetofclassesthatshouldbelongtoasuite.
1. OpentheNewwizard
2. SelectJava>JUnit>JUnitTestSuiteandclickNext.
3. Enteranameforyourtestsuiteclass(theconventionistouse"AllTests"whichappearsbydefault).
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 46/322
12/10/2015 Javadevelopmentuserguide
4. Selecttheclassesthatshouldbeincludedinthesuite.Wecurrentlyhaveasingletestclassonly,butyoucanaddtothesuitelater.
Youcanaddorremovetestclassesfromthetestsuiteintwoways:
Manuallybyeditingthetestsuitefile
Byrerunningthewizardandselectingthenewsetoftestclasses.
Note:thewizardputs2markers,//$JUnitBEGIN$and//$JUnitEND$,intothecreatedTestsuiteclass,whichallowsthewizardtoupdateexistingtestsuiteclasses.Editingcode
betweenthemarkersisnotrecommended.
NextSection:Projectconfigurationtutorial
2.2.Projectconfigurationtutorial
Inthissection,youwillcreateandconfigureanewJavaprojecttousesourcefoldersandtomatchsomeexistinglayoutonthefilesystem.Sometypicallayoutshavebeen
identified.Choosethesubsectionthatmatchesyourlayout.
NextSection:Detectingexistinglayout
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.1.Detectingexistinglayout
Layoutonfilesystem
Thesourcefilesforaproductarelaidoutinonedirectory"src".
Theclassfilesareinanotherdirectory"bin".
Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 47/322
12/10/2015 Javadevelopmentuserguide
3. Type"Product"intheProjectnamefield.
4. InProjectlayoutgroup,changeselectiontoCreateseparatesourceandoutputfolders.
DeselectUsedefaultlocation.
ClickBrowse...andchoosetheProductdirectoryondriveD:.
5. ClickNext.
Ensurethatthesourceandoutputfoldersaredetected.
Warning:IftheScruboutputfolderswhencleaningprojectspreferenceintheOutputfoldersectionofthe Java>Compiler>Buildingpreferencepageischecked,
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 48/322
12/10/2015 Javadevelopmentuserguide
clickingFinishwillscrubthe"bin"directoryinthefilesystembeforegeneratingtheclassfiles.
6. ClickFinish.
7. YounowhaveaJavaprojectwitha"src"folderwhichcontainsthesourcesofthe"Product"directory.
Note:Thissolutioncreatesa".project"fileanda".classpath"fileinthe"Product"directory.Ifyoudonotwishtohavethesefilesinthe"Product"directory,youshoulduselinked
foldersasshownintheSiblingproductsinacommonsourcetreesection.
NextSection:Organizingsources
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.2.Organizingsources
Layoutonfilesystem
Inthissection,youwillcreateanewJavaprojectandorganizeyoursourcesinseparatefolders.Thiswillprepareyouforhandlingmorecomplexlayouts.
Let'sassumeyouwanttoputyoursourcesinonefolderandyourtestsinanotherfolder:
Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"MyProject"intheProjectnamefield.
4. InProjectlayoutgroup,changeselectiontoCreateseparatesourceandoutputfoldersandeditConfiguredefault...tomodifySourcefoldernamefrom"src"to
"sources".
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 49/322
12/10/2015 Javadevelopmentuserguide
5. ClickOKtoreturnonNewJavaProjectwizardandthenclickNext.
6. Toaddanothersourcefoldertoyourproject,clickCreatenewsourcefolderlinkinDetailspaneorbutton inviewbar.
7. InNewSourceFolderdialog,type"tests"intheFoldernamefield.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 50/322
12/10/2015 Javadevelopmentuserguide
8. ClickFinishtovalidateandclosethedialog.
9. Yourprojectsetupnowlooksasfollows:
10. ClickFinish
11. YounowhaveaJavaprojectwithtwosourcefolders:sourcesandtests.Youcanstartaddingclassestothesefoldersoryoucancopythemusingdraganddrop.
NextSection:Siblingproductsinacommonsourcetree
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.3.Siblingproductsinacommonsourcetree
Layoutonfilesystem
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 51/322
12/10/2015 Javadevelopmentuserguide
ThesourcefilesforproductsarelaidoutinonebigdirectorythatisversionandconfigurationmanagedoutsideEclipse.
ThesourcedirectorycontainstwosiblingsdirectoriesProduct1andProduct2.
Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.
4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 52/322
12/10/2015 Javadevelopmentuserguide
5. InLinkSourcedialogclickBrowse....andchoosetheD:\AllProducts\Product1\JavaSourceFilesdirectory.
6. ClickFinishtovalidateandclosethedialog.
7. Yourprojectsourcesetupnowlooksasfollows:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 53/322
12/10/2015 Javadevelopmentuserguide
8. ClickFinish.
9. Repeatsteps2to8for"Product2".
10. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"Product1"and"Product2".
NextSection:Overlappingproductsinacommonsourcetree
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.4.Overlappingproductsinacommonsourcetree
Layoutonfilesystem
TheJavasourcefilesforproductsareallheldinasinglemaindirectory.
ProductsareseparatedintofoursiblingspackagesProduct1,Product2,Product3andProduct4.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 54/322
12/10/2015 Javadevelopmentuserguide
Stepsfordefiningcorresponding"Product1"and"Product2"projects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.
4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 55/322
12/10/2015 Javadevelopmentuserguide
5. InLinkSourceclickBrowse....andchoosetheD:\AllJavaSourceFilesdirectory.
Type"src"inFoldername.
6. ClickFinishtovalidateandclosethedialog.
7. Expandthe"src"sourcefolder.SelectthethreelastpackagesandexcludethemfrombuildpathusingeitherExcludefrombuildpathlinkorExcludepopupmenuitem.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 56/322
12/10/2015 Javadevelopmentuserguide
8. Yourprojectsourcesetupnowlooksasfollows:
9. ClickFinish.
10. Copy"Product1"projectandpasteitas"Product2".
Edit"Product2"projectpropertiesandgoonJavaBuildPathpage.
InSourcetab,expand"Product2/src"sourcefolder,selectExcludedandclickEdit....
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 57/322
12/10/2015 Javadevelopmentuserguide
11. InInclusionandExclusionPatterns,select"com/xyz/product2"andclickEdit....
12. Change"com/xyz/product2"to"com/xyz/product1".
13. ClickOKtoenterthechange.
ClickFinishtovalidateandcloseInclusionandExclusionPatternsdialog.
ClickOKagaintovalidate"Product2"projectpropertieschanges.
14. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"product1","product2".
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 58/322
12/10/2015 Javadevelopmentuserguide
NextSection:Productwithnestedtests
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.5.Productwithnestedtests
Layoutonfilesystem
TheJavasourcefilesforaproductarelaidoutinapackagedirectory.
Sourcefilesoftestsarelaidoutinanestedpackagedirectory.
Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 59/322
12/10/2015 Javadevelopmentuserguide
4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
5. InLinkSourceclickBrowse....andchoosetheD:\Product1\JavaSourceFilesdirectory.
Type"src"intheFoldernamefield.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 60/322
12/10/2015 Javadevelopmentuserguide
6. ClickFinishtovalidateandclosethedialog.
7. Expandthe"src"sourcefolder.Selecttheemptypackage"tests"andsetitassourcefolderusingeitherUseasSourceFolderpopupmenuitemorbutton inviewbar.
8. Yourprojectsourcesetupnowlooksasfollows:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 61/322
12/10/2015 Javadevelopmentuserguide
9. ClickFinish.
10. YounowhaveaJavaprojectwithtwosourcefolders:"src"and"src/tests"whichcontainrespectivelytheD:\Product1\JavaSourceFilesdirectoryandthe
D:\Product1\JavaSourceFiles\testsdirectory.
NextSection:Productssharingacommonsourceframework
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.6.Productssharingacommonsourceframework
Layoutonfilesystem
TheJavasourcefilesfortwoproductsrequireacommonframework.
Projectsandcommonframeworkareinseparatedirectorieswhichhavetheirownsourceandoutputfolders.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 62/322
12/10/2015 Javadevelopmentuserguide
Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.
4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 63/322
12/10/2015 Javadevelopmentuserguide
5. InLinkSourceclickBrowse....andchoosetheD:\Product1\JavaSourceFilesdirectory.
Type"src"intheFoldernamefield.
6. ClickFinishtovalidateandclosethedialog.
7. Again,Select"Product1"andclickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 64/322
12/10/2015 Javadevelopmentuserguide
8. InLinkSourceclickBrowse....andchoosetheD:\Framework\JavaSourceFilesdirectory.
Type"srccommon"intheFoldernamefield.
9. ClickFinishtovalidateandclosethedialog.
Yourprojectsourcesetupnowlooksasfollows:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 65/322
12/10/2015 Javadevelopmentuserguide
10. ClickFinish.
11. Createproject"Product2"repeatingsteps2to5choosingD:\Product2\JavaSourceFilesdirectoryforsourcefolderinstead.
12. ClickonFinishtocreatetheprojectimmediately.
13. Now,we'llseehowtoaddalinkedsourcefolderwhenprojectisalreadycreatedinworkspace...
Editproject"Product2"propertiesandselectJavaBuilderPathpage.
OnSourcetab,clickLinkSource....
14. InLinkSourceclickBrowse....andchoosetheD:\Framework\JavaSourceFilesdirectory.
Type"srccommon"intheFoldernamefield.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 66/322
12/10/2015 Javadevelopmentuserguide
15. ClickFinishtovalidateandclosethedialog.
ClickOKtoapplyproject"Product2"propertieschanges.
16. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"Product1"and"Product2"andwhichareusingthesourcesof"Framework".
Note:Filesin"srccommon"areshared.Soediting"Common.java"in"Product1"willmodify"Common.java"in"Product2".Howevertheyarecompiledinthecontextoftheir
respectiveprojects.Two"Common.class"fileswillbegeneratedoneforeachproject.Ifthetwoprojectshavedifferentcompileroptions,thendifferenterrorscouldbereportedon
each"Common.java"file.
NextSection:Productnestingresourcesinoutputdirectory
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.7.Nestingresourcesinoutputdirectory
Layoutonfilesystem
TheJavasourcefilesforaproductarelaidoutbothinsourcesanddeliverablesdirectories.
AllJavaclassfilesarelaidoutindeliverablesdirectory.
Projectneedstousesomelibrarieslocatedindeliverables/librariesdirectory:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 67/322
12/10/2015 Javadevelopmentuserguide
Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product"intheProjectnamefield.ClickNext.
4. Onthenextpage,Type"Product/deliverables"inDefaultoutputfolderfield.
Select"Product"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 68/322
12/10/2015 Javadevelopmentuserguide
5. InLinkSourceclickBrowse....andchoosetheD:\Product\sourcesdirectory.
6. ClickFinishtovalidateandclosethedialog.
7. Again,Select"Product"andclickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 69/322
12/10/2015 Javadevelopmentuserguide
8. InLinkSourceclickBrowse....andchoosetheD:\Product\deliverablesdirectory.
9. Expandthe"Product/deliverables"sourcefolder.Selectthe"libraries"packageandexcludeitfrombuildpathusingeitherExclude'libraries'frombuildpathlinkorExclude
popupmenuitem.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 70/322
12/10/2015 Javadevelopmentuserguide
10. Yourprojectsourcesetupnowlooksasfollows:
11. SelectLibrariestab.
ClickonAddJARs....
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 71/322
12/10/2015 Javadevelopmentuserguide
12. Expand"Product"hierarchytoselectjarfilesin"libraries"directory
ClickOK.
13. ClickFinishtofinalizeprojectcreation.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 72/322
12/10/2015 Javadevelopmentuserguide
14. YounowhaveaJavaprojectwitha"sources"folderandanoutputfolderwhichcontainsnestedlibraryresources.
NextSection:Projectusingasourceframeworkwithrestrictedaccess
Javaprojects
Javaviews
NewJavaProjectWizard
PackageExplorerView
2.2.8.Projectusingasourceframeworkwithrestrictedaccess
Layoutonfilesystem
TheJavasourcefilesforaproductrequiresasourceframework.
"Product"and"Framework"areinseparatedirectorieswhichhavetheirownsourceandoutputfolders.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 73/322
12/10/2015 Javadevelopmentuserguide
Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Framework"intheProjectnamefield.
4. DeselectUsedefaultlocation.
ClickBrowse...andchoosetheD:\Frameworkdirectory.
ClickNext.
5. Onthenextpage,verifythatdirectoryJavaSourceFileshasbeenautomaticallyaddedassourcefolder.
Expandittopreviewyourprojectsourcefoldercontents:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 74/322
12/10/2015 Javadevelopmentuserguide
6. ClickFinish.
7. InJavaperspective,typeCtrl+NtoopenNewwizardsdialog.
SelectJavaprojectinthelistofwizardsandclickNext.
8. Onthenextpage,type"Product"intheProjectnamefield.
9. DeselectUsedefaultlocation.
ClickBrowse...andchoosetheD:\Productdirectory.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 75/322
12/10/2015 Javadevelopmentuserguide
10. ClickNext.
11. Onthenextpage,verifythatdirectoryJavaSourceFileshasbeenautomaticallyaddedassourcefolder.
Expandittopreviewyourprojectsourcefoldercontents:
12. SelectProjectstab.
ClickAdd...toaddadependencytosourceframeworkproject...
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 76/322
12/10/2015 Javadevelopmentuserguide
13. InRequiredProjectSelection,check"Framework".
14. ClickOKtovalidateandclosedialog.
15. Now,let'sputaccessrulesonsourceframeworkcontenttoauthorize,discourageorforbidaccessto"Framework"sourcefolders,packageandclasses...
InProjectstab,select"Accessrules"of"Framework"dependingproject.
ClickEdit....
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 77/322
12/10/2015 Javadevelopmentuserguide
16. InTypeAccessRules,clickAdd....
17. InAddAccessRule,select"Forbidden"forResolution.
Type"**/forbidden/**"inRulePatternfield.
18. ClickOKtovalidateaccessruleandclosedialog.
19. Addanotheraccessrule:
Resolution:"Discouraged"andRulePattern:"**/internal/**".
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 78/322
12/10/2015 Javadevelopmentuserguide
20. Youraccessrulesnowlookasfollows:
21. ClickOKtovalidatethesenewrulesandclosedialog.
22. Dependentprojecthasnow2accessrulesset.
23. ClickFinish.
24. YounowhaveaJavaprojectwhichcontainsthesourceof"Product"andwhichisusingthesourceof"Framework".
Somepackagesoftheproject"Framework"arerestrictedandifyoutrytoimportthem,compilerdisplayseitherwarningsorerrorsdependingonyourrestrictionlevel:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 79/322
12/10/2015 Javadevelopmentuserguide
NextSection:EclipseandJ2SE5.0
Javaprojects
NewJavaProjectWizard
PackageExplorerView
2.3.EclipseandJ2SE5.0
Sincerelease3.1,EclipseincludesfullsupportforthenewJavalanguagefeaturesofJ2SE5.0.Oneofthemostimportantconsequencesofthissupportisthatyoumaynotnoticeit
atalleverythingyouexpecttoworkforJ2SE1.4,includingediting,compiling,debugging,quickfixes,refactorings,sourceactions,searching,etc.,willworkseamlesslywithJ2SE
5.0'snewtypesandsyntax.Inthisdocument,wewillintroducesomeofthemoreinterestingcapabilitiesEclipseuserswillfindwhenworkingwithJ2SE5.0.
Notethatbothversionnumbers'1.5'and'5.0'areusedtoidentifythereleaseoftheJava2PlatformStandardEdition.Version'5.0'istheproductversion,while'1.5'isthedeveloper
versionandisalsousedforthecompliancelevel.
Prerequisites
InordertodevelopcodecompliantwithJ2SE5.0,youwillneedaJ2SE5.0orJ2SE6.0JavaRuntimeEnvironment(JRE).IfyoustartEclipseforthefirsttimeusingaJ2SE5.0
JRE,thenitwilluseitbydefault.Otherwise,youwillneedtousethe Java>InstalledJREspreferencepagetoregisteritwithEclipse.
ThisdocumentintroducessomeofthenewlanguagefeaturesinJ2SE5.0verybriefly,butitisnotapropertutorialforthesefeatures.Seehereformoreinformation.
CompilerComplianceLevel
TousethenewJ2SE5.0features,youmustbeworkingonaprojectthathasa1.5compliancelevelenabledandhasa5.0JRE.Newprojectswillautomaticallyget1.5compliance
whenchoosinga5.0JREonthefirstpageofthe NewJavaProjectwizard:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 80/322
12/10/2015 Javadevelopmentuserguide
ToconvertanexistingJ2SE1.4projecttoJ2SE5.0,youcansimply:
1. MakesureyouhaveaJ2SE5.0JREinstalled.
2. Startusingthe5.0featuresinyourcode.
3. Whenacompileerrorisflagged,useQuickFixtoupdatetheproject'scompliancelevel:
4. Formorefinetunedcontrol,thecompilercompliancelevelcanbesetgloballyforaworkspace(withthe Java>Compilerpreferencepage)orindividuallyforeachproject
(fromtheproject'scontextmenu,chooseProperties>JavaCompiler).
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 81/322
12/10/2015 Javadevelopmentuserguide
Projectswithdifferentcompliancelevelscancoexistintheworkspace,anddependoneachother.Youcanalsofinetunethekindsofcompilewarningsanderrorsproducedforeach
projectusingProperties>JavaCompiler>Errors/Warnings.TheGenericTypesandtheAnnotationssectioncontainoptionsaddedforJ2SE5.0.
GenericTypes
Generictypesallowobjectsofthesameclasstosafelyoperateonobjectsofdifferenttypes.Forexample,theyallowcompiletimeassurancesthataList<String>alwayscontains
Strings,andaList<Integer>alwayscontainsIntegers.
AnywherethatEclipsehandlesanongenerictype,itcanhandleagenerictype:
Generictypescanbesafelyrenamed.
Typevariablescanbesafelyrenamed.
Genericmethodscanbesafelyextractedfrom/inlinedintogenericcode.
Codeassistcanautomaticallyinsertappropriatetypeparametersinparameterizedtypes.
Inaddition,anewrefactoringhasbeenadded:InferGenericTypeArgumentscaninfertypeparametersforeverytypereferenceinaclass,apackage,oranentireproject.
Invokingtherefactoringproduces:
Eclipseprovidesnewoptionswhensearchingforreferencestogenerictypes.Considerthisexample:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 82/322
12/10/2015 Javadevelopmentuserguide
SelectingthereferencetoList<Integer>andusingSearch>References>ProjectfromthecontextmenuwillhighlighttheListtypesonallfourlines:
UsingtheSearchViewmenu,theresultscanbefiltered:
FilterIncompatibleTypeArgumentsleavesonlyreferencestotypesthatareassignmentcompatiblewiththeselectedtype:
FilterInexactTypeArgumentsleavesonlytypereferenceswiththeexactsamesignature:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 83/322
12/10/2015 Javadevelopmentuserguide
Annotations
AnnotationsattachmetadataabouthowJavatypesandmethodsareusedanddocumentedtotheJavasourceandcanthenaffectcompilationorbequeriedatruntime.For
example,@Overridewilltriggeracompilewarningiftheannotatedmethoddoesnotoverrideamethodinasuperclass:
EverythingyoucandowithaJavatype,youcandowithanannotation:
CreatenewannotationsusingNew>Annotation
Refactor:rename,move,changesignaturesofmembers,etc.
Searchforoccurrences
Usecodeassisttofillinnamesandvalues
AveryusefulannotationwithfullsupportinEclipseis@SuppressWarnings.Forexample,consideraprivatemethodthatiscurrentlyunused,butyou'drathernotdelete:
Invokingquickfixonthewarningproposesaddinga@SuppressWarningsannotation:
Selectingthequickfixaddstheannotation.TheEclipsecompilerhonorstheannotationbyremovingthewarningonfoo:
Enumerations
Enumerationsaretypesthatareinstantiatedatruntimebyaknown,finitesetofobjects:
Again,anythingyoucandotoaJavaclasscanbedonetoanenumeration:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 84/322
12/10/2015 Javadevelopmentuserguide
CreatenewenumerationsusingNew>Enum
Refactor:rename,move,renameconstants,etc.
Searchforoccurrences
Usecodeassisttofillinconstants
Autoboxing
AutoboxingandautounboxingallowforelegantsyntaxwhenprimitivetypesareassignedtoorretrievedfromObjectreferences:
Eclipse'ssourcemanipulationfeatureshandleautoboxingseamlessly,givingthecorrecttypestonewlocalvariablesandcorrectcodeassists.Forcodeunderstanding,itisalso
possibletoflaginstancesofautoboxingorautounboxingconversions:
markthemascompilewarningsorerrors(BoxingandunboxingconversionsinthePotentialProgrammingProblemssectionofthe Java>Compiler>
Errors/Warningspreferencepage)
highlightthemusingsyntaxcoloring(viatheJava>Auto(un)boxedexpressionssectionofthe Java>Editor>SyntaxColoringpreferencepage):
Enhancedforloop
Forthecommoncaseofoperatingoneachelementofanarrayorcollectioninturn,J2SE5.0allowsanew,cleanersyntax.Eclipseprovidesa"foreach"codetemplatethatcan
automaticallyguessthecollectiontobeiterated:
Choosingthetemplateproduces:
Eclipsealsoprovidesa"Converttoenhancedforloop"quickassisttoupgrade1.4styleforloopswherepossible.
StaticImports
Staticimportsallowyoutousestaticfieldsandmethodsfromotherclasseswithoutqualification.
ContentassistintheJavaeditorcansuggestsuchstaticmembersandaddsastaticimportwhenrequired.Togetsuchproposals,configurethestaticimportfavoritesonthe
Java>Editor>ContentAssist>Favoritespreferencepage.
ConvertingJ2SE1.4codeto5.0
EclipseoffersthefollowingtoolstohelpyoubringJ2SE1.4codeto5.0:
CleanUpaction
Addmissing@Overrideand@Deprecatedannotations
Convertforloopstoenhanced
InferGenericTypeArgumentsrefactoring
Happycoding!
2.4.EclipseandJava7
Sincerelease3.7.1,EclipseincludesfullsupportforthenewJavalanguagefeaturesofJavaSE7.Oneofthemostimportantconsequencesofthissupportisthatyoumaynot
noticeitatalleverythingyouexpecttoworkforJava6,includingediting,compiling,debugging,quickfixes,refactorings,sourceactions,searching,etc.,willworkseamlesslywith
Java7'snewsyntax.Inthisdocument,wewillintroducesomeofthemoreinterestingcapabilitiesEclipseuserswillfindwhenworkingwithJava7.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 85/322
12/10/2015 Javadevelopmentuserguide
Notethatbothversionnumbers'1.7'and'7'areusedtoidentifythereleaseoftheJavaPlatformStandardEdition.Version'7'istheproductversion,while'1.7'isthedeveloper
versionandisalsousedforthecompilercompliancelevel.
Prerequisites
InordertodevelopcodecompliantwithJava7,youwillneedaJava7JavaRuntimeEnvironment(JRE).IfyoustartEclipseforthefirsttimeusingaJava7JRE,thenitwilluseit
bydefault.Otherwise,youwillneedtousethe Java>InstalledJREspreferencepagetoregisteritwithEclipse.
YoucanalsoconfigureaJava7executionenvironment,viathe Java>InstalledJREs>ExecutionEnvironmentspreferencepage:
ToconvertanexistingJavaprojecttoJava7,openthePropertiesoftheJRESystemLibraryandchooseExecutionenvironment:JavaSE1.7.
TheexecutionenvironmentAPIdescriptionforJava7isavailablefromthecorrespondingupdatesite.Afterinstallingit,onecandetectinvalidreferencestoJava7systemlibraries:
Java7languagefeatures
Java7comeswithasetofsmallenhancementstotheJavalanguage(akaProjectCoin),anewbytecodetodynamicallyinvokemethods,andmanyadditionstothelibraries.This
documentintroducessomeofthenewlanguagefeaturesinJava7verybriefly,butitisnotapropertutorialforthesefeatures.Seehereformoreinformation.
ImprovedTypeInferenceforGenericInstanceCreation(Diamond)
Multicatch
trywithresourcesstatement
SimplifiedVarargsMethodInvocation
Stringsinswitch
BinaryLiteralsandUnderscoresinNumericLiterals
PolymorphicMethods
ImprovedTypeInferenceforGenericInstanceCreation(Diamond)
Thislanguagechangeallowsexplicittypeargumentstoconstructorsofparameterizedclassestobeomittedinmanysituations.Thecompilerinferstheomittedtypearguments
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 86/322
12/10/2015 Javadevelopmentuserguide
basedontheexpectedtype.
Wherepossible,contentassistforconstructorinvocationsinsertsadiamondinsteadofexplicittypearguments.
Result:
Thecompilercanalsodetectredundantspecificationoftypearguments,whichyoucanremoveviatheRemovetypeargumentsquickfix.
Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>Errors/Warningspreferencepage:
Inaddition,youcanalsoinsertinferredtypeargumentsofadiamondviaaquickassist.
Hint:Thisalsoworksasaquickfixin1.5and1.6code,wherethediamondisasyntaxerror.
Multicatch
InJava7youcancatchmultipleexceptiontypesusingasinglecatchblock.
MarkOccurrencesinJavaeditorcanbeusedtohighlightstatementswhichthrowaparticularexception.
TheSource>SurroundWith>Try/multicatchBlockactionallowsyoutosurroundselectedstatementswithatry/multicatchblock.ThisisalsoavailableasSurroundwith
try/multicatchquickfixincasetherearemultipleuncaughtexceptions.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 87/322
12/10/2015 Javadevelopmentuserguide
TheAddexceptionstoexistingcatchclausequickfixallowsyoutoadduncaughtexceptionstoanexistingcatchclause.
TheUseseparatecatchblocksquickassistallowsyoutoreplaceamulticatchclausewithindividualcatchblocks,oneforeachexceptioninthemulticatchclause.
TheMoveexceptionstoseparatecatchblockquickassistallowsyoutopickoutoneormoreselectedexceptionsfromamulticatchclause.
TheCombinecatchblocksquickassistallowsyoutocombineseparatecatchblocksintoasinglemulticatchblock.Thequickassistisofferedonlywhenbodiesofallthecatch
blocksaresame.
Thecompilerreportsanerrorifanexceptioninamulticatchclauseisalreadycaughtbyanalternativeexception.TheRemoveexceptionquickfixallowsyoutoremovethis
exception.
Inaddition,thereareLineWrappingoptionsintheformatterforthemulticatchsyntax.Thesecanbeconfiguredonthe Java>CodeStyle>Formatterpreferencepageunder
LineWrapping>Statements>'multicatch'.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 88/322
12/10/2015 Javadevelopmentuserguide
trywithresourcesstatement
Thetrywithresourcesstatementensuresthateachresourceajava.lang.AutoCloseableisclosedattheendofthestatement.
MarkOccurrencesintheJavaeditorunderstandsthetrywithresourcessyntax.Theclosing'}'ofatrywithresourcesstatementismarkedasamethodexitpointiftheimplicit
close()invocationthrowsanexception.Thecorrespondingresourcevariableisalsohighlighted.
Thecompilerdetectsunhandledexceptionsthrownbyautomaticclose()invocationonaresource.
Thecompilercansuggestusingtrywithresourcesstatementwhentheresourceshavebeenexplicitlyclosedbutnotdeclaredintrywithresourcesstatements.
Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>Errors/Warningspreferencepage:
Inaddition,thereareLineWrappingandWhiteSpaceoptionsintheformatterforthetrywithresourcessyntax.Thesecanbeconfiguredonthe Java>CodeStyle>
FormatterpreferencepageunderLineWrapping>Statements>'trywithresources'andWhiteSpace>ControlStatements>'trywithresources'.
SimplifiedVarargsMethodInvocation
TheJava7compliergeneratesawarningatthedeclarationsiteofavarargsmethodorconstructorwithanonreifiablevarargsformalparameter.Thiswarningcanbesuppressed
usingthe@SafeVarargsannotation.
TheAdd@SafeVarargsquickfixisofferedforpotentialheappollutionwarningsonmethoddeclarations.
Thequickfixisalsoofferedfromcallsites.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 89/322
12/10/2015 Javadevelopmentuserguide
TheRemove@SafeVarargsquickfixisofferedforincorrectusageof@SafeVarargsannotation.
Stringsinswitch
YoucanuseaStringobjectintheexpressionofaswitchstatement.
TheConvert'switch'to'ifelse'quickassistworksforstringsinswitch.
NotethatthequickassistavoidsaNullPointerExceptionintheresultantcode.
BinaryLiteralsandUnderscoresinNumericLiterals
InJava7,theintegraltypes(byte,short,int,andlong)canalsobeexpressedusingthebinarynumbersystem.Inaddition,anynumberofunderscorecharacters(_)canappear
anywherebetweendigitsinanumericalliteral.
Thefeatureforchangingthevalueofavariablewhiledebuggingsupportsunderscoresinnumericliteralsandbinaryliterals:
PolymorphicMethods
Javadochoversforreferencestopolymorphicmethodsshowtheactuallyusedmethodsignature.
Happycoding!
3.1.JavaProjects
AJavaprojectcontainssourcecodeandrelatedfilesforbuildingaJavaprogram.IthasanassociatedJavabuilderthatcanincrementallycompileJavasourcefilesastheyare
changed.
AJavaprojectalsomaintainsamodelofitscontents.Thismodelincludesinformationaboutthetypehierarchy,referencesanddeclarationsofJavaelements.Thisinformationis
constantlyupdatedastheuserchangestheJavasourcecode.TheupdatingoftheinternalJavaprojectmodelisindependentoftheJavabuilderinparticular,whenperformingcode
modifications,ifautobuildisturnedoff,themodelwillstillreflectthepresentprojectcontents.
YoucanorganizeJavaprojectsintwodifferentways:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 90/322
12/10/2015 Javadevelopmentuserguide
Usingtheprojectasthesourcecontainer.Thisistherecommendedorganizationforsimpleprojects.
Usingsourcefoldersinsidetheprojectasthesourcecontainer.Thisistherecommendedorganizationformorecomplexprojects.Itallowsyoutosubdividepackagesinto
groups.
Javabuilder
NewJavaprojectwizard
3.2.JavaBuilder
TheJavabuilderbuildsJavaprogramsusingitsowncompiler(theEclipseCompilerforJava)thatimplementstheJavaLanguageSpecification.TheJavabuildercanbuildprograms
incrementallyasindividualJavafilesaresaved.NotethattheEclipseCompilerforJavacanalsobeinvokedusingAntasdescribedintheUsingtheantjavacadaptersection.
Problemsdetectedbythecompilerareclassifiedaseitherwarningsorerrors.Theexistenceofawarningdoesnotaffecttheexecutionoftheprogramthecodeexecutesasifit
werewrittencorrectly.Compiletimeerrors(asspecifiedbytheJavaLanguageSpecification)arealwaysreportedaserrorsbytheJavacompiler.Forsomeothertypesofproblems
youcan,however,specifyifyouwanttheJavacompilertoreportthemaswarnings,errorsortoignorethem.Tochangethedefaultsettings,usethe Java>Compiler>
Errors/Warningspreferencepage.
TheJavacompilercancreateCLASSfileseveninpresenceofcompilationerrors.However,inthecaseofseriouserrors(forexample,referencestoinconsistentbinaries,most
likelyrelatedtoaninvalidbuildpath),theJavabuilderdoesnotproduceanyCLASSfiles.
Buildclasspath
Usingthebatchcompiler
Usingtheantjavacadapter
ExcludingwarningsusingSuppressWarnings
Javabuildpathproperties
Javacompilerpreferences
3.2.1.BuildClasspath
ThebuildclasspathspecifieswhichJavasourcefilesandresourcefilesinaprojectareconsideredbytheJavabuilderandspecifieshowtofindtypesoutsideoftheproject.The
JavabuildercompilestheJavasourcefilesintotheoutputfolderandalsocopiestheresourcesintoit.Thebuildclasspathisspecifiedforeachproject.Intheprojectproperties,itis
referredtoastheJavaBuildPath
Javabuilder
Classpathvariables
Inclusionandexclusionpatterns
Accessrules
Classpathvariablespreferences
Javabuildpathproperties
3.2.1.1.InclusionandExclusionPatterns
InclusionandExclusionpatternscanbeconfiguredforsourcefolders.TheydefinewhichfilesareconsideredbytheJavabuilderandotherJavatooling.Thissetoffilesconsistsof
allfilesandfolderswherethepathrelativetothesourcefoldermatchesaninclusionpatternbutnotanexclusionpattern.
Bydefault,allfilesandfolderscontainedinasourcefolderareincluded.Bydefininganinclusionpattern,thesetofincludedresourceswillbelimitedtotheresourcesmatchingthe
inclusionpattern.Usingexclusionpatterns,someoftheseresourcescanbeexcludedagain.
Exclusionpatternsarerequiredwhennestingsourcefolders.Thenestedfoldermustbeexcludedfromtheoutersourcefolder.
ThepatternshavethesameformatasANTpatterns:
'*'matcheszeroormorecharacters,'?'matchesonecharacter.
'/'isusedtoseparatefolders:Thismeansthefirstsegmentinthepatternismatchedagainstthemostouterfoldernameinthepathtomatch,thesecondsegmentwiththe
second,andsoon.
'**'matchesanynumberoffolders
Javabuilder
Classpathvariables
Accessrules
JavaBuildPathproperties
3.2.1.2.AccessRules
Accessrulescanbeaddedtobuildclasspathentriestospecifywhichtypesinthegivenentrycanbeaccessedandwhichnot.Ifthecompilerdetectsatypeaccesstoatypethat
shouldnotbeaccessed,itwillcreateaproblemmarker.
Nonaccessiblerulesdefinetypesthatmustnotbereferenced.Thecompilertypicallycreatesanerrormarkerforaccessestothesetypes.
Discouragedrulesdefinetypesthatshouldnotbereferenced.Thecompilertypicallycreatesawarningmarkerforaccessestothesetypes.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 91/322
12/10/2015 Javadevelopmentuserguide
Accessiblerulesdefinetypesthatcanbereferenced.
Eachruleconsistofapattern(sameformatasANTpatterns)andoneoftheruletypeslistedabove.
Eachclasspathentrycanhaveanynumberofrulesdefined.Thecompilerwillprocessthelistintheorderdefinedandtakethefirstmatchingrule.
Theseverityoftheproblemmarkergeneratedforaccessesto'Nonaccessible'and'Discouraged'typecanbeconfiguredontheJavacompiler'sError/Warningspreferencepage.
CombineAccessRules
Javabuilder
Classpathvariable
Inclusionandexclusionpatterns
Javabuildpathproperties
Error/Warningspreferencepage
3.2.1.3.ClasspathVariables
ThebuildpathforaJavaprojectcanincludesourcecodefiles,otherJavaprojects,folderscontainingclassfilesandJARfiles.JARfilescanbespecifiedusingfilesystempaths,or
byusingvariablesthatrefertolocationsonthenetwork.
ClasspathvariablesallowyoutoavoidreferencestothelocationofaJARfileorfoldersonyourlocalfilesystem.Byusingaclasspathvariable,youcanspecifyaJARfileorfolder
usingonlyavariablename,suchasJRE_LIB,ratherthanspecifyingthelocationonyourworkstation.Inthisway,youcansharebuildpathsacrossteamsanddefinethevariables
torefertothecorrectlocationforyourparticularcomputer.
Javabuilder
Classpathvariable
Inclusionandexclusionpatterns
Accessrules
Classpathvariablespreferences
Javabuildpathproperties
3.3.JavaPerspectives
TheJavadevelopmenttoolscontributethefollowingperspectivestotheworkbench:
Java
AperspectivedesignedforworkingwithJavaprojects.Itconsistsofaneditorareaandthefollowingviews:
PackageExplorer
Outline
Problems
Javadoc
Declaration
JavaBrowsing
AperspectivedesignedforbrowsingthestructureofJavaprojects.Itconsistsofaneditorareaandthefollowingviews:
Projects
Packages
Types
Members
JavaTypeHierarchy
Aperspectivedesignedforexploringatypehierarchy.Itcanbeopenedontypes,compilationunits,packages,projectsorsourcefoldersandconsistsoftheTypeHierarchyviewand
aneditor.
Debug
AperspectivedesignedfordebuggingyourJavaprogram.Itincludesaneditorareaandthefollowingviews.
Debug
Breakpoints
Variables
Expressions
Outline
Console
Tasks
Javaviews
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 92/322
12/10/2015 Javadevelopmentuserguide
Breakpointsview
Consoleview
Debugview
Displayview
Expressionsview
Javaoutline
PackageExplorerview
TypeHierarchyview
Variablesview
3.4.JavaViews
TheJavadevelopmenttoolscontributethefollowingviewstotheworkbench:
Java
PackageExplorerView
ThePackageExplorerviewshowsaJavaspecificviewofresourcesinsideJavaprojectsinyourworkbench.TheJavaelementhierarchyisdefinedbytheproject'sbuildclass
pathsandconsistsofelementslike
sourcefoldersandlibraries
packages
sourceandclassfiles
types,methods,fieldsandinitializers
TypeHierarchyView
TheTypeHierarchyviewallowsyoutolookatthecompletehierarchyforatype,onlyitssubtypes,oronlyitssupertypes.Youcanalsoopenthehierarchyonaproject,source
folderorpackage.
CallHierarchyView
TheCallHierarchyviewallowsyoutolookatthecallersandcalleesforaselectedJavamember.
JavaOutlineView
TheJavaoutlineviewdisplaysanoutlineofthestructureofthecurrentlyactiveJavafileintheeditorarea.
JUnitView
TheJUnitviewshowsyoutheJUnittestrunprogressandstatus,andallowsyoutoreruntests.
JavadocView
TheJavadocviewshowstheJavadocoftheelementselectedintheJavaeditororinaJavaview.
DeclarationView
TheDeclarationviewshowsthesourceoftheelementselectedintheJavaeditororinaJavaview.
JavaBrowsing
ProjectsView
TheProjectsviewshowsJavaprojects,sourcefolders,externalandinternallibraries.
Note:sourcefoldersandlibraries(bothinternalandexternal)presentedinthisviewarenotexpandable.Whentheyareselected,theircontentsareshowninthePackages
view.
PackagesView
ThePackagesviewshowsalistofJavapackagesfromthecurrentlyselectedJavaprojects,sourcefoldersorlibraries.Typically,theProjectsviewisusedtomakethis
selection.
TypesView
TheTypesviewshowsalistofJavatypesfromthecurrentlyselectedpackages.Typically,thePackagesviewisusedtomakethisselection.
MembersView
TheMembersviewshowsthecontentofatype,compilationunitorCLASSfile.Typically,theTypesviewisusedtomakethisselection.
Debug
DebugView
TheDebugviewallowsyoutomanagethedebuggingorrunningofaprogramintheworkbench.Itdisplaysthestackframeforthesuspendedthreadsforeachtargetyouare
debugging.Eachthreadinyourprogramappearsasanodeinthetree.Itdisplaystheprocessforeachtargetyouarerunning.
BreakpointsView
TheBreakpointsviewlistsallthebreakpointsyoucurrentlyhavesetinyourworkspace.Youcanalsoenableordisablebreakpoints,deletethem,addnewones,groupthemby
workingset,orconfigureattributesofaselectedbreakpoint.
ExpressionsView
DatacanbeinspectedintheExpressionsview.Youcaninspectdatafromascrapbookpage,astackframeofasuspendedthread,andotherplaces.TheExpressionsView
opensautomaticallywhenanitemisaddedtotheview.EntriesintheExpressionsViewcanbeselectedtohavemoredetailedinformationbedisplayedintheDetailPane.
WhendebuggingaJavaprogram,datathatcontainsvariablescanbeexpandedtoshowthevariablesandthefieldsthevariablescontain.
VariablesView
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 93/322
12/10/2015 Javadevelopmentuserguide
TheVariablesviewdisplaysinformationaboutthevariablesassociatedwiththestackframeselectedintheDebugView.WhendebuggingaJavaprogram,variablescanbe
selectedtohavemoredetailedinformationbedisplayedintheDetailPane.Inaddition,Javaobjectscanbeexpandedtoshowthefieldsthatvariablecontains.
ConsoleView
TheConsoleviewdisplaysavarietyofconsoletypesdependingonthetypeofdevelopmentandthecurrentsetofusersettings.Theconsolesthatareprovidedbydefaultwith
theEclipsePlatformare:
TheProcessConsole
TheStacktraceConsole
TheCVSConsole
TheOSGiConsole
DisplayView
TheDisplayviewdisplaystheresultofevaluatinganexpressioninthecontextofthecurrentstackframe.Youcanevaluateanddisplayaselectioneitherfromtheeditoror
directlyfromtheDisplayView.
ViewCustomization
BoththeappearanceandbehavioroftheJavaviewscanbecustomized.
Filtering
Sorting
Javaelementdecorations
Presentationoptions
Javaperspectives
ChangingtheappearanceoftheConsoleview
Viewsandeditors
3.4.1.FilteringinJavaViews
ApplyingViewFilters
AllJavaviewsallowtofilterthedisplayedJavaelements.Thesetofavailablefiltersdependsontheview.
Tofilterelements:
1. Ontheviewtoolbar,clicktheMenubuttonandchooseFilters....
2. Selectorclearthefiltersthatyouwanttoapplytotheview(readFilterdescriptiontolearnabouttheselectedfilter'sfunctionality).
3. Optionally,youcanselectpatternsforfilteringtheview:
SelecttheNamefilterpatternscheckboxatthetopofthedialog.
Inthetextfieldbelow,specifythedesiredpatterns(namesmatchingoneofthepatternswillbehidden).
FilteringMembers
SeveralJavaviews(e.g.Outline,TypeHierarchy,Members)offerfilteringofmembers(fields,typesandmethods).Thefiltersareavailableastoolbarbuttonsorasviewmenu
items,dependingontheview.Thereare3memberfilters:
HideFields:whenactivated,thisfiltercausesallfieldstoberemovedfromtheview.
HideStaticFieldsandMethods:whenactivated,thisfiltercausesallstaticmemberstoberemovedfromtheview.
HideNonPublicMembers:whenactivated,thisfiltercausesallnonpublicmemberstoberemovedfromtheview.
Additionally,thePackageExplorerviewcandisplayorhideallelementsinsidecompilationunits.
ToshoworhidemembersinthePackageExplorerview,selectorcleartheShowmembersinPackageExplorercheckboxinthe Java>Appearancepreferencepage.
FilteringWorkingSets
SeveralJavaviews(e.g.PackageExplorer,TypeHierarchy)offertofilterbyoneormoreworkingsets.Thefiltersareavailableintheviewmenu.Onlytheelementsthatare
containedintheselectedworkingsetsareshownintheview.
Javaprojects
Workingsets
PackageExplorer
3.4.2.SortinginJavaViews
TheMembersandOutlineviewscanpresentmemberssortedorintheorderofdeclarationinthecompilationunit.
Tosortmembers:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 94/322
12/10/2015 Javadevelopmentuserguide
ToggleontheSorttoolbarbuttonintheviewtoolbar.
Thesortingordercanbeconfiguredontheonthe Java>Appearance>MembersSortOrderpreferencepage.
Aftertheabovesortingisperformed,membersineachgrouparesortedalphabetically.
Topresentmembersintheorderofdeclarationinthecompilationunit.
ToggleofftheSorttoolbarbuttonintheviewtoolbar.
Javatoolbaractions
3.4.3.JavaElementDecorations
OverrideIndicators
Javaviewscanshowspecialdecorationiconstoindicatemethodsthatoverrideorimplementmethodsfromsupertypes.
Toshoworhidetheoverrideindicators,selectorcleartheJavaMethodOverrideIndicatorcheckboxinthe General>Appearance>LabelDecorationspreferencepage.
JavaTypeIndicator
ThepackageexplorercanindicatethekindofJavatype(Enum,Interface,Annotation)containedinaJavafile.
Note:
IfaJavafilecontainsmorethanonetopleveltype,itisdecoratedaccordingtoitsprimarytype.
Nodecorationisshownforclasses,exceptforabstractclasses.
ToshoworhidetheJavatypeindicators,selectorcleartheJavaTypeIndicatorcheckboxinthe General>Appearance>LabelDecorationspreferencepage.
Appearancepreferencepage
PackageExplorer
3.4.4.PresentationOptionsforJavaViews
ShowingandHidingMethodReturnTypes
SeveralJavaviews(e.g.Outline,Members)presentmethodsandcanalsoshowtheirreturntypesandtypeparameters.
ToshowmethodreturntypesinJavaviewsselectorcleartheShowmethodreturntypesorShowmethodtypeparameterscheckboxinthe Java>Appearancepreference
page.
ShowingFullorCompressedPackageNames
ThePackageExplorerandPackagesviewscanshowfullorcompressedpackagenames.
Toshowfullpackagenames:
CleartheCompressallpackagenamesegments,exceptthefinalsegmentcheckboxonthe Java>Appearancepreferencepage.
Toshowcompressedpackagenames:
SelecttheCompressallpackagenamesegments,exceptthefinalsegmentcheckboxonthe Java>Appearancepreferencepage.
Compressionpatternscontrolhowmanycharactersofeachpackagenamesegmentaredisplayed.Thelastsegmentofapackagenameisalwaysdisplayed.
Acompressionpatternof"."indicatesthatonlytheseparatingperiodsareshowntorepresentasegment.Adigit(n)inacompressionpatternrepresentsthefirstncharactersof
apackagenamesegment.Examplesarethebestwaytounderstandcompressionpatterns.Thepackageorg.eclipse.jdtwouldbedisplayedasfollowsusingtheexample
compressionpatterns:
...jdt
0jdt
2~or~.ec~.jdt
3~org.ecl~.jdt
Javaappearancepreferencepage
PackageExplorer
3.5.JavaEditor
TheJavaeditorprovidesspecializedfeaturesforeditingJavacode.
AssociatedwiththeeditorisaJavaspecificOutlineview,whichshowsthestructureoftheactiveJavacompilationunit.Itisupdatedastheusereditsthecompilationunit.
Theeditorcanalsoshowabreadcrumbnavigationbar.Thebreadcrumbshowstheparentchainoftheelementatthecurrentcursorposition.Itisalsoupdatedwhentheuseredits
thecompilationunitorchangestheselection.
TheJavaeditorcanbeopenedonbinaryCLASSfiles.IfaJARfilecontainingtheCLASSfileshasasourceattachment,thentheeditorshowsthecorrespondingsource.
Theeditorincludesthefollowingfeatures:
Syntaxhighlighting
Content/codeassist
Codeformatting
Importassistance
Quickfix
Integrateddebuggingfeatures
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 95/322
12/10/2015 Javadevelopmentuserguide
TheJavaeditorcanbeconfiguredtoeithershowanentirecompilationunitorasingleJavaelementonly.Tochangethesetting,usethetoolbarbuttonShowSourceofSelected
ElementOnly.
ThemostcommonwaytoinvoketheJavaeditoristoopenaJavafilefromthePackageExplorerusingpopupmenusorbyclickingthefile(singleordoubleclickdependingonthe
userpreferences).YoucanalsoopentheeditorbyopeningJavaelements,suchastypes,methods,orfields,fromotherviews.
Quickfixandassist
Templates
Openinganeditorforaselectedelement
Viewingruntimeexceptions
Evaluatingexpressions
Quickassists
Quickfixes
Javaeditoractions
Javaeditorpreferences
Javaoutline
JavaEditorBreadcrumb
Viewsandeditors
3.6.QuickFixandQuickAssist
Formostproblemsunderlinedwithaproblemhighlightline,theJavaeditorcanoffercorrections.Thisisshownbythelightbulbshownintheeditormarkerbar.
ToseethecorrectionproposalsusetheQuickFixaction
Setthecursorinsideornearthehighlightrange,andselectQuickFixfromtheEditmenuorthecontextmenu.
Setthecursorinsideornearthehighlightrange,andpressCtrl+1
Clickonthelightbulb
QuickfixisalsoavailableonaproblementryintheProblemsview.TheQuickFixactionwillopenadialogtoselectthecorrection.
Notethatthelightbulbisonlyahint.Itispossiblethatevenwiththelightbulbshown,itturnsoutthatnocorrectionscanbeoffered.
AoverviewofquickfixesavailableintheJavaeditorcanbefoundhere.
QuickAssistsareproposalsavailableevenifthereisnoproblemorwarning.TheyusethesameshortcutandactionlikeQuickFix.Quickassistsareusedforlocalcode
manipulations.SeetheQuickassistreferenceformoreinformation.
Javaeditor
Quickassists
Quickfix
Javaeditorpreferences
Editmenu
3.7.EditorTemplates
Templatesareastructureddescriptionofcodingpatternsthatreoccurinsourcecode.TheJavaeditorsupportstheuseoftemplatestofillincommonlyusedsourcepatterns.
Templatesareinsertedusingcontentassist(Ctrl+Space).
Forexample,acommoncodingpatternistoiterateovertheelementsofanarrayusingaforloopthatindexesintothearray.Byusingatemplateforthispattern,youcanavoid
typinginthecompletecodefortheloop.Invokingcontentassistaftertypingthewordforwillpresentyouwithalistofpossibletemplatesforaforloop.Youcanchoosethe
appropriatetemplatebyname(iterateoverarray).Selectingthistemplatewillinsertthecodeintotheeditorandpositionyourcursorsothatyoucaneditthedetails.
Templatescancontaintemplatevariables.Variablesmarktheeditablelocations.Theycanberesolvedtoaconcretevaluewhenthetemplateisevaluatedinitscontext.Theycan
alsoprovidealistofalternativeproposalsvalidatthegivenlocation.
Manycommontemplatesarealreadydefined.Thesecanbeviewedwiththe Java>Editor>Templatespreferencepage.Youcanalsocreateyourowntemplatesoreditthe
existingones.
Templatespreferences
Templatevariables
Templateediting
Editmenu
Javacontentassist
3.7.1.JavaEditorTemplateVariables
GeneralTemplateVariables
JavaSpecificTemplateVariables
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 96/322
12/10/2015 Javadevelopmentuserguide
Templatevariablesmaybeusedinthetemplatepattern.Variablesareresolvedtotheirconcretevaluewhenthetemplateisevaluatedinitscontext.Variablesmaybespecified
usingsimpleorfullsyntax:
Simplevariablestakethefollowingform:
${array}
Thisdefinesavariablewithnamearraythatwillresolvetoanarray.Itcanbereferencedmultipletimesasis.
Fullvariablestakethefollowingform:
${it:var(java.util.Iterator)}
Thisdefinesavariablewithnameitthatwillresolvetoalocalvariableoftypejava.util.Iterator.Itcanbereferencedmultipletimesbysimplygivingitsnamewithoutthe
type:${it}.
Argumentstoafullvariablecanbewrittenverbatimiftheyarequalifiednamesorintegers.Ifanargumentincludesothercharactersorspaces,thenithastobeenclosedin
singlequotes''.
Ifthereareseveralpossiblematchesforavariable,theymaybepresentedasproposalstotheuser.
GeneralTemplateVariables
BothJavaandJavadoccontextdefinethefollowingvariables:
Variable Description
${cursor} Specifiesthecursorpositionwhenthetemplateeditmodeisleft.Thisisusefulwhenthecursorshouldjumptoanotherplacethantotheend
ofthetemplateonleavingtemplateeditmode.
${date} Evaluatestothecurrentdate.
${dollar} Evaluatestothedollarsymbol$.Alternatively,twodollarscanbeused:$$.
${enclosing_method} Evaluatestothenameoftheenclosingmethod.
${enclosing_method_arguments} Evaluatestoacommaseparatedlistofargumentnamesoftheenclosingmethod.Thisvariablecanbeusefulwhengeneratinglogstatements
formanymethods.
${enclosing_package} Evaluatestothenameoftheenclosingpackage.
${enclosing_project} Evaluatestothenameoftheenclosingproject.
${enclosing_type} Evaluatestothenameoftheenclosingtype.
${file} Evaluatestothenameofthefile.
${line_selection} Evaluatestocontentofallcurrentlyselectedlines.
${primary_type_name} Evaluatestothenameprimarytypeofthecurrentcompilationunit.
${return_type} Evaluatestothereturntypeoftheenclosingmethod.
${time} Evaluatestothecurrenttime.
${user} Evaluatestotheusername.
${word_selection} Evaluatestothecontentofthecurrenttextselection.
${year} Evaluatestothecurrentyear.
JavaSpecificTemplateVariables
TheJavacontextadditionallydefinesthefollowingvariables.Note:Inthetablebelow,idisauserchosennameofanewvariable.
Variable Description
${id:field(type[,type]*)} Evaluatestoafieldinthecurrentscopethatisasubtypeofanyofthegiventypes.Ifnotypeisspecified,anynonprimitive
fieldmatches.
Example:
${count:field(int)}
${id:var(type[,type]*)} Evaluatestoafield,localvariableorparametervisibleinthecurrentscopethatisasubtypeofanyofthegiventypes.Ifno
typeisspecified,anynonprimitivevariablematches.
Example:
${container:var(java.util.List,'java.lang.Object[]')}
${id:localVar(type[,type]*)} Evaluatestoalocalvariableorparametervisibleinthecurrentscopethatisasubtypeofanyofthegiventype.Ifnotypeis
specified,anynonprimitivelocalvariablematches.
${array}isashortcutfor${array:localVar('java.lang.Object[]')},butalsomatchesarraysofprimitivetypes.
${collection}isashortcutfor${collection:localVar(java.util.Collection)}.
${iterable}isashortcutfor${iterable:localVar(java.lang.Iterable)},butalsomatchesarrays.
${id:argType(variable,n)} Evaluatestothenthtypeargumentofthereferencedtemplatevariable.Thereferenceshouldbethenameofanother
templatevariable.Resolvestojava.lang.Objectifthereferencedvariablecannotbefoundorisnotaparameterizedtype.
Example:
${type:argType(vector,0)}${first:name(type)}=${vector:var(java.util.Vector)}.get(0)
${id:elemType(variable)} Evaluatestotheelementtypeofthereferencedtemplatevariable.Thereferenceshouldbethenameofanothertemplate
variablethatresolvestoanarrayoraninstanceofjava.lang.Iterable.TheelemTypevariabletypeissimilarto
${id:argType(reference,0)},thedifferencebeingthatitalsoresolvestheelementtypeofanarray.
${array_type}isashortcutfor${array_type:elemType(array)}.
${iterable_type}isashortcutfor${iterable_type:elemType(iterable)}.
${id:newName(reference)} Evaluatestoanonconflictingnameforanewlocalvariableofthetypespecifiedbythereference.Thereferencemayeither
beaJavatypenameorthenameofanothertemplatevariable.Thegeneratednamerespectsthecodestylesettings.
${index}isashortcutfor${index:newName(int)}.
${iterator}isashortcutfor${iterator:newName(java.util.Iterator)}.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 97/322
12/10/2015 Javadevelopmentuserguide
${array_element}isashortcutfor${array_element:newName(array)}.
${iterable_element}isashortcutfor${iterable_element:newName(iterable)}.
${id:newType(qualifiedTypeName)} EvaluatestoatypenamegiventhefullyqualifiedJavatypename.Evaluatestoasimpletypenameandanimportifno
conflictingtypeexists.Evaluatestoafullyqualifiedtypenameotherwise.
Example:
${type:newType(java.util.Iterator)}
${:import(type[,type]*)} Addsanimportstatementforeachtype.Doesnothingiftheimportalreadyexists.Doesnothingifaconflictingimport
exists.Evaluatestonothing.
Example:
${:import(java.util.List,java.util.Collection)}
${:importStatic([qualifiedName[,qualifiedName]*])} Addsastaticimportstatementforeachqualifiednamethatisnotalreadyimported.ThequalifiedNameisthefullyqualified
nameofastaticfieldormethod,oritisthequalifiednameofatypeplusa.*suffix,enclosedinsinglequotes''.Does
nothingifaconflictingimportexists.Evaluatestonothing.
Example:
${is:importStatic(java.util.Collections.EMPTY_SET,'java.lang.System.*')}
${id:link(proposal[,proposal]*)} Evaluatestoidifthelistofproposalsisempty,evaluatestothefirstproposalotherwise.Theevaluatedvalueisputinto
linkedmode.Aproposalwindowshowsallthegivenproposals.
Example:
java.util.Collections.${kind:link(EMPTY_SET,EMPTY_LIST,EMPTY_MAP)}
${array} Evaluatestoaproposalforanarrayvisibleinthecurrentscope.
${array_element} Evaluatestoanameforanewlocalvariableforanelementofthe${array}variablematch.
${array_type} Evaluatestotheelementtypeofthe${array}variablematch.
${collection} Evaluatestoaproposalforacollectionvisibleinthecurrentscope.
${exception_variable_name} Exceptionvariablenameincatchblocks.
${index} Evaluatestoaproposalforanundeclaredarrayindex.
${iterator} Evaluatestoanunusednameforanewlocalvariableoftypejava.util.Iterator.
${iterable} Evaluatestoaproposalforaniterableorarrayvisibleinthecurrentscope.
${iterable_element} Evaluatestoanameforanewlocalvariableforanelementofthe${iterable}variablematch.
${iterable_type} Evaluatestotheelementtypeofthe${iterable}variablematch.
${todo} Evaluatestoaproposalforthecurrentlyspecifieddefaulttasktag.
Templates
Editingtemplates
Templatespreferencepage
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences
3.8.JavaSearch
TheJavasearchingsupportallowsyoutofinddeclarations,referencesandoccurrencesofJavaelements(packages,types,methods,fields).Searchingissupportedbyanindex
thatiskeptuptodateinthebackgroundastheresourcescorrespondingtoJavaelementsarechanged.TheJavasearchoperatesonworkspacesindependentoftheirbuildstate.
Forexample,searchescanbeconductedwhenautobuildisturnedoff.
ThefollowingsearchescanbeinitiatedfromthepopupmenusofJavaelementsorfromtheJavasearchdialog:
Command Description
References FindsallreferencestotheselectedJavaelement
Declarations FindsalldeclarationsoftheselectedJavaelement
Implementors FindsallimplementorsoftheselectedJavainterface
Readaccess FindsallreadaccessestotheselectedJavafield
Writeaccess FindsallwriteaccessestotheselectedJavafield
Matchlocationsfortypereferences Findsalltypereferencesatspecifiedlocations(incasts,asfieldtype,...)
OccurrencesinFile FindsalloccurrencesoftheselectedJavaelementinitsfile
Thescopeofthesearchisdefinedas:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 98/322
12/10/2015 Javadevelopmentuserguide
Workspaceallprojectsandfilesintheworkspaceareincludedinthissearch
EnclosingProjectstheprojectsenclosingthecurrentlyselectedelements
Hierarchyonlythetypehierarchyoftheselectedelementisincludedinthissearch
WorkingSetonlyresourcesthatbelongtothechosenworkingsetareincludedinthissearch
Searchactions
Javasearchtab
3.9.RefactoringSupport
ThegoalofJavaprogramrefactoringistomakesystemwidecodechangeswithoutaffectingthebehavioroftheprogram.TheJavatoolsprovideassistanceineasilyrefactoring
code.
TherefactoringtoolssupportanumberoftransformationsdescribedinMartinFowler'sbookRefactoring:ImprovingtheDesignofExistingCode,AddisonWesley1999,suchas
ExtractMethod,InlineLocalVariable,etc..
TogetanoverviewofallofferedrefactoringslookattheRefactormenu.Refactoringcommandsarealsoavailablefromthecontextmenusinmanyviewsorappearasquick
assists.
Whenperformingarefactoringoperation,youcanoptionallypreviewallofthechangesresultingfromarefactoringactionbeforeyouchoosetocarrythemout.Whenpreviewinga
refactoringoperation,youwillbenotifiedofpotentialproblemsandwillbepresentedwithalistofthechangestherefactoringactionwillperform.Ifyoudonotpreviewarefactoring
operation,thechangewillbemadeinitsentiretyandanyresultantproblemswillbeshown.Ifaproblemisdetectedthatdoesnotallowtherefactoringtocontinue,theoperationwill
behaltedandalistofproblemswillbedisplayed.
RefactoringcommandsareavailablefromthecontextmenusofseveralJavaviews(e.g.PackageExplorer,Outline)andeditors.Many"apparentlysimple"commands,suchas
MoveandRename,areactuallyrefactoringoperations,sincemovingandrenamingJavaelementsoftenrequirechangesindependentfiles.
Refactoringscannotonlybeperformedinteractively,butalsofromrefactoringscripts.MostrefactoringsavailableintheRefactormenuarestoredintheworkspacerefactoring
historyinordertobeusedinrefactoringscriptsafterwards.Therefactoringtoolssupportthecreationofrefactoringscriptsbasedonrefactoringsintheworkspacerefactoringhistory.
Refactoringscriptscanthenbeappliedtoanarbitraryworkspace.Applyingarefactoringscriptlaunchesarefactoringwizardwhichisabletoreplaytherefactoringsasiftheyhad
beeninitiatedbytheuserwhichoriginallyhadcreatedthem.
Relatedtorefactoringscripts,therefactoringtoolsofferarefactoringtomigrateaJARFiletoanewerversion,usingrefactoringinformationtoavoidbreakingchangesinyour
workspaceafterthemigration.
Refactoringactions
Refactoringwizard
Javapreferences
3.10.Debugger
TheJavadevelopmenttoolkit(JDT)includesadebuggerthatenablesyoutodetectanddiagnoseerrorsinyourprogramsrunningeitherlocallyorremotely.
Thedebuggerallowsyoutocontroltheexecutionofyourprogrambysettingbreakpoints,suspendinglaunchedprograms,steppingthroughyourcode,andexaminingthecontentsof
variables.
Thedebuggerhasaclient/serverdesignsoyoucandebugprogramsrunningremotelyonothersystemsinthenetworkaswellasprogramsrunninglocallyonyourworkstation.The
debugclientrunsinsidetheworkbenchonyourworkstation.Thedebuggerserverrunsonthesamesystemastheprogramyouwanttodebug.Thiscouldbeaprogramlaunchedon
yourworkstation(localdebugging)oraprogramstartedonacomputerthatisaccessiblethroughanetwork(remotedebugging).
Javadevelopmenttools(JDT)
Breakpoints
Remotedebugging
Localdebugging
Addingbreakpoints
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
Evaluatingexpressions
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads
Debugpreferences
Debugview
Runmenuactions
RunandDebugtoolbaractions
3.11.Scrapbook
TheJavadevelopmenttoolkit(JDT)contributesascrapbookfacilitythatcanbeusedtoexperimentandevaluateJavacodesnippetsbeforebuildingacompleteJavaprogram.
SnippetsareeditedandevaluatedintheScrapbookpageeditor,withresultantproblemsreportedintheeditor.
FromaJavascrapbookeditor,youcanselectacodesnippet,evaluateit,anddisplaytheresultasastring.Youcanalsoshowtheobjectthatresultsfromevaluatingacodesnippet
inthedebuggers'ExpressionsView.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 99/322
12/10/2015 Javadevelopmentuserguide
Javadevelopmenttools(JDT)
Debugger
CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
NewJavaScrapbookPagewizard
JavaScrapbookpage
Expressionsview
3.12.LocalDebugging
TheJavadebuggerhasaclient/serverdesignsothatitcanbeusedtodebugprogramsthatrunlocally(onthesameworkstationasthedebugger)orremotely(onanothercomputer
onthenetwork).
Localdebuggingisthesimplestandmostcommonkindofdebugging.AfteryouhavefinishededitingandbuildingyourJavaprogram,youcanlaunchtheprogramonyour
workstationusingthe Run>DebugConfigurations...menuitemontheworkbench.Launchingtheprograminthiswaywillestablishaconnectionbetweenthedebuggerclient
andtheJavaprogramthatyouarelaunching.Youmaythenusebreakpoints,stepping,orexpressionevaluationtodebugyourprogram.
Breakpoints
Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads
Debugpreferences
Debugview
Runmenuactions
RunandDebugtoolbaractions
3.13.RemoteDebugging
Theclient/serverdesignoftheJavadebuggerallowsyoutolaunchaJavaprogramfromcomputeronyournetworkanddebugitfromtheworkstationrunningtheplatform.Thisis
particularlyusefulwhenyouaredevelopingaprogramforadevicethatcannothostthedevelopmentplatform.Itisalsousefulwhendebuggingprogramsondedicatedmachines
suchaswebservers.
Note:Touseremotedebugging,youmustbeusingaJavaVMthatsupportsthisfeature.
Todebugaprogramremotely,youmustbeabletolaunchtheprogramindebugmodeontheremotemachinesothatitwillwaitforaconnectionfromyourdebugger.Thespecific
techniqueforlaunchingtheprogramandconnectingthedebuggerareVMspecific.Thebasicstepsareasfollows:
1. EnsurethatyouarebuildingyourJavaprogramwithavailabledebuginformation.(Youcancontroltheseattributesfromthe Java>Compilerpreferencepage).
2. AfteryoubuildyourJavaprogram,installittothetargetcomputer.Thisinvolvescopyingthe.CLASSfilesor.JARfilestotheappropriatelocationontheremotecomputer.
3. InvoketheJavaprogramontheremotecomputerusingtheappropriateVMargumentstospecifydebugmodeandacommunicationportforthedebugger.
4. Startthedebuggerusingaremotelaunchconfigurationandspecifytheaddressandportoftheremotecomputer.
Whensettinguptheremotelaunchconfigurationthereareafewitemstotakenoteof:
Youmustensureyouenterthecorrecthostnamei.e.thenameoftheremotecomputerwhereyouarecurrentlyrunningyourcode.ThehostnamecanalsobetheIPaddressof
theremotemachine,forexampleusing127.0.0.1insteadoflocalhost.
Theportnumbermustbethenumberoftheportontheremotemachine.
CertainJavaVMssupportanotherwayofstartingaremotedebugsession.Inthisalternativeconnectiontype,thedebuggerislaunchedfirst.Thedebuggerthenwaitsandlistensfor
theVMtoconnecttoit.Todebugthisway,youmustproperlyconfigureandlauncharemotedebugsession,thenlaunchtheVM,specifyingthelocationofyourwaitingdebugger.
Formoreinformation,seeUsingtheremoteJavaapplicationlaunchconfiguration.
UsingtheremoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
3.14.Breakpoints
Abreakpointsuspendstheexecutionofaprogramatthelocationwherethebreakpointisset.
BreakpointscanbeenabledanddisabledviathecontextmenuintheBreakpointsView,orviathecontextmenuintheJavaEditorruler.
Anenabledbreakpointcausesathreadtosuspendwheneverthebreakpointisencountered.Enabledbreakpointsaredrawnwithabluecircle[ ]andhaveacheckmark
overlayoncesuccessfullyinstalled.AbreakpointcanonlybeinstalledwhentheclassthebreakpointislocatedinhasbeenloadedbytheVM.
Adisabledbreakpointwillnotcausethreadstosuspend.Disabledbreakpointsaredrawnwithawhitecircle[ ].
BreakpointsaredisplayedintheverticaleditorrulerandintheBreakpointsview.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 100/322
12/10/2015 Javadevelopmentuserguide
Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads
Debugpreferences
Debugview
Runmenuactions
Runanddebugtoolbaractions
Breakpointsview
3.15.StringExternalization
TheJavatoolshelpyoutodevelopapplicationsthatcanberunoninternationalplatforms.Animportantfacetofdesigningaprogramforuseindifferentcountriesisthelocalization,
orexternalization,oftextthatisdisplayedbytheprogram.Byexternalizingstrings,thetextcanbetranslatedfordifferentcountriesandlanguageswithoutrebuildingtheJava
program.
TheJDTprovidesthefollowingsupportforinternationalizationandstringexternalization:
Acompileroptionletsyoumarknonexternalizedstringsascompiletimewarningsorerrors.
SeetheNonexternalizedstringsoptionintheCodestylesectionofthe Java>Compiler>Errors/Warningspreferencepage.
Toolsthatallowyoutofindstringsthathavenotbeenexternalized.
Awizardthatwillguideyouthroughexternalizingthestrings.
Toolsthathelpyoutofindunusedandincorrectlyusedkeysforstringslocatedinpropertyfiles.
Commentscanbeusedtodenotestringsthatshouldnotbeexternalizedandshouldnotresultincompiletimewarningsorerrors.Thesecommentsareofform//$NONNLSn$
wherenisthe1basedindexofthestringinalineofcode.
Additionalinformationaboutinternationalizedapplicationscanbefoundinthefollowingdocuments:
http://eclipse.org/articles/ArticleInternationalization/how2I18n.html
http://download.oracle.com/javase/tutorial/i18n/
Findingstringstoexternalize
Findingunusedandincorrectlyusedkeysinpropertyfiles
Sourcemenu
Externalizestringswizard
Javacompilerpreferences
4.1.1.Changingtheactiveperspectivewhenlaunching
Youcancontrolwhichperspectivebecomesactivewhenaprogramislaunchedandwhenitsuspends.Thesettingisconfigurableforeachlaunchconfigurationtype,foreachofthe
launchmodesitsupports.
Toactivateaparticularperspectivewhenaprogramislaunched,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. SelecttheAlwaysoptionfortheOpentheassociatedperspectivewhenlaunchingpreference.Thiswillcausetheperspectiveassociatedwithaprogramtobecomeactive
wheneveritislaunched.
Toactivateaparticularperspectivewhenaprogramissuspends,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. SelecttheAlwaysoptionfortheOpentheassociatedperspectivewhenanapplicationsuspendspreference.Thiswillcausetheperspectiveassociatedwithaprogramto
becomeactivewheneveraprogramsuspends.
Toassociateaparticularperspectivewithaprogram,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. Selectthetypeofapplicationthatyouwouldliketoassociateaperspectivewith(forexample,JavaApplication).
3. Foreachlaunchmode,selectthedesiredperspectiveusingthecombobox.Thiswillcausetheperspectiveyouchoosetobecomeactivebasedonyourpreferencesettings
(i.e.whenaprogramislaunchedand/orwhenitsuspends).
Ifthespecifiedperspectiveisnotopenatthetimeitneedstobeactivated,thatperspectiveiscreated.
Debugger
Remotedebugging
Localdebugging
Javaperspectives
Runninganddebugging
Settingexecutionarguments
LaunchingaJavaprogram
Consoleview
Debugpreferences
Debugview
RunMenu
4.1.2.Changingtheappearanceoftheconsoleview
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 101/322
12/10/2015 Javadevelopmentuserguide
Tosetthetypesofoutput(andtheircolors)intheConsoleview:
1. Openthe Run/Debug>Consolepreferencepage.
2. CheckingtheShowwhenprogramwritestostandardoutcheckboxwillmaketheConsoleviewvisibleeachtimenewoutputiswrittentotheconsolefromtheprogram's
standardoutputstream.IfthereisnoConsoleviewinthecurrentperspective,onewillbecreated.
3. CheckingtheShowwhenprogramwritestostandarderrcheckboxwillmaketheConsoleviewvisibleeachtimenewoutputiswrittentotheconsolefromtheprogram's
standarderrorstream.IfthereisnoConsoleviewinthecurrentperspective,onewillbecreated.
4. Clickanyofthecolorbuttonstochangethecolorforthecorrespondingtextstream.
TosetthefontsusedintheConsoleview:
1. Openthe General>Appearance>ColorsandFontspreferencepage.
2. SelectConsolefontfromtheDebugcategoryandusetheChange...buttontochangethefont.(TheDetailPaneTextFontcanbeusedtochangethefontofthe
debugger'sdefaultDetailPane).
Debugger
Javaviews
Consoleview
Viewsandeditors
4.2.CreatingJARFiles
YoucancreateandregenerateJARfilesintheworkbench.
CreatinganewJARfile
RegeneratingaJARfile
CreatinganewRunnableJARfile
JARfileexporter
RunnableJARfileexporter
4.2.1.CreatingaNewJARFile
TocreateanewJARfileintheworkbench:
1. InthePackageExplorer,youcanoptionallypreselectoneormoreJavaelementstoexport.(Thesewillbeautomaticallyselectedinthe JARPackageSpecification
wizardpage,describedinStep4.)
2. Eitherfromthecontextmenuorfromthemenubar'sFilemenu,selectExport.
3. ExpandtheJavanodeandselectJARfile.ClickNext.
4. IntheJARFileSpecificationpage,selecttheresourcesthatyouwanttoexportintheSelecttheresourcestoexportfield.
5. SelecttheappropriatecheckboxtospecifywhetheryouwanttoExportgeneratedclassfilesandresourcesorExportJavasourcefilesandresources.Note:Selected
resourcesareexportedinbothcases.
6. IntheSelecttheexportdestinationfield,eithertypeorclickBrowsetoselectalocationfortheJARfile.
7. SelectorcleartheCompressthecontentsoftheJARfilecheckbox.
8. SelectorcleartheOverwriteexistingfileswithoutwarningcheckbox.Ifyouclearthischeckbox,thenyouwillbepromptedtoconfirmthereplacementofeachfilethatwill
beoverwritten.
9. Note:TheoverwriteoptionisappliedwhenwritingtheJARfile,theJARdescription,andthemanifestfile.
10. Youhavetwooptions:
ClickFinishtocreatetheJARfileimmediately.
ClickNexttousetheJARPackagingOptionspagetosetadvancedoptions,createaJARdescription,orchangethedefaultmanifest.
Settingadvancedoptions
DefiningtheJARfile'smanifest
RegeneratingaJARfile
JARfileexporter
PackageExplorer
4.2.2.SettingAdvancedOptions
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. IfyouwanttosavetheJARfiledescription,selecttheSavethedescriptionofthisJARintheworkspacecheckbox.AJARfiledescriptioncanbeusedtoregeneratea
JARfilewithoutusingthewizard.
3. ThecompilerisabletogenerateCLASSfilesevenwhensourcecontainserrors.YouhavetheoptiontoexcludeCLASS(butnotsource)fileswithcompileerrors.Thesefiles
willbereportedattheend,ifreportingisenabled.
4. YoucanchoosetoexcludeCLASS(butnotsource)filesthathavecompilewarnings.Thesefileswillbereportedattheend.
Note:Thisoptiondoesnotautomaticallyexcludeclassfileswithcompileerrors.
5. YoucanchoosetoincludethesourcefolderpathbyselectingtheCreatesourcefolderstructurecheckbox.
6. SelecttheBuildprojectsifnotbuiltautomaticallycheckboxifyouwanttheexporttoperformabuildbeforecreatingtheJARfile.
7. ClickFinishtocreatetheJARfileimmediatelyorNextifyouwanttochangethedefaultmanifest.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 102/322
12/10/2015 Javadevelopmentuserguide
CreatinganewJARfile
DefiningtheJARfile'smanifest
RegeneratingaJARfile
JARfileexporter
4.2.3.DefiningtheJARFile'sManifest
YoucaneitherdefinetheimportantpartsoftheJARfilemanifestdirectlyinthewizardorchoosetouseamanifestfilethatalreadyexistsinyourworkbench.
Creatinganewmanifest
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. Setanyadvancedoptionsthatyouwanttoset,andthenclickNextagaintogototheJARManifestSpecificationpage.
3. Ifitisnotalreadyselected,clicktheGeneratethemanifestfilebutton.
4. Youcannowchoosetosavethemanifestintheworkbench.Thiswillsavethemanifestforlateruse.ClickSavethemanifestintheworkspace,thenclickBrowsenextto
theManifestfilefieldtospecifyapathandfilenameforthemanifest.
5. IfyoudecidedtosavethemanifestfileinthepreviousstepandyouchosetosavetheJARdescriptiononthepreviouswizardpage,thenyoucanchoosetoreuseitinthe
JARdescription(byselectingtheReuseandsavethemanifestintheworkspacecheckbox).ThismeansthatthesavedfilewillbeusedwhentheJARfileisrecreatedfrom
theJARdescription.ThisoptionisusefulifyouwanttomodifyorreplacethemanifestfilebeforerecreatingtheJARfilefromthedescription.
6. YoucanchoosetosealtheJARandoptionallyexcludesomepackagesfrombeingsealedorspecifyalistwithsealedpackages.Bydefault,nothingissealed.
7. ClicktheBrowsebuttonnexttotheMainclassfieldtospecifytheentrypointforyourapplications.
Note:Ifyourclassisnotinthelist,thenyouforgottoselectitatthebeginning.
8. ClickFinish.ThiswillcreatetheJAR,andoptionallyaJARdescriptionandamanifestfile.
Usinganexistingmanifest
Youcanuseanexistingmanifestfilethatalreadyexistsinyourworkbench.
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. Setanyadvancedoptionsthatyouwanttoset,andtheclickNextagaintogototheJARManifestSpecificationpage.
3. ClicktheUseexistingmanifestfromworkspaceradiobutton.
4. ClicktheBrowsebuttontochooseamanifestfilefromtheworkbench.
5. ClickFinish.ThiswillcreatetheJARandoptionallyaJARdescription.
CreatinganewJARfile
Settingadvancedoptions
RegeneratingaJARfile
JARfileexporter
4.2.4.RegeneratingaJARFile
YoucanuseaJARfiledescriptiontoregenerateapreviouslycreatedJARfile.
1. SelectoneormoreJARfiledescriptionsinyourworkbench.
2. Fromtheselection'spopupmenu,selectCreateJAR.TheJARfile(s)areregenerated.
CreatinganewJARfile
DefiningtheJARfile'smanifest
JARfileexporter
4.2.5.CreatingaNewRunnableJARFile
TocreateanewrunnableJARfileintheworkbench:
1. Fromthemenubar'sFilemenu,selectExport.
2. ExpandtheJavanodeandselectRunnableJARfile.ClickNext.
3. Inthe RunnableJARFileSpecificationpage,selecta'JavaApplication'launchconfigurationtousetocreatearunnableJAR.
4. IntheExportdestinationfield,eithertypeorclickBrowsetoselectalocationfortheJARfile.
5. Selectanappropriatelibraryhandlingstrategy.
6. Optionally,youcanalsocreateanANTscripttoquicklyregenerateapreviouslycreatedrunnableJARfile.
RunnableJARfileexporter
4.3.UsingtheLocalHistory
TheJDTextendstheworkbenchconceptofalocalhistoryinthreeways:
AfilecanbereplacedwithaneditionfromthelocalhistoryinthePackageExplorerview.
TheJDTallowsyoutocompareand/orreplaceindividualJavaelements(typesandtheirmembers)witheditionsfromthelocalhistory.
TheJDTallowsyoutorestoreJavaelements(andfiles)deletedfromtheworkbenchthathavebeenkeptinthelocalhistory.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 103/322
12/10/2015 Javadevelopmentuserguide
Note:FilesandJavaelementssuchastypesandtheirmemberschangeintime.A'snapshot'ofwhattheylooklikeapointintime(assavedinthelocalhistory)iscalledanedition.
Javadevelopmenttools(JDT)
Javaviews
ReplacingaJavaelementwithalocalhistoryedition
ComparingaJavaelementwithalocalhistoryedition
Restoringadeletedworkbenchelement
PackageExplorer
4.3.1.ComparingaJavaElementWithaLocalHistoryEdition
1. MakesurethataJavaviewisvisible.
2. OpenaJavaeditorfortheJavafileinwhichyouwanttocompareaJavaelementwithaneditionfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea.TheOutlineviewalsodisplaystheJavafile.Note:ThePackageExplorercanbeconfiguredtoshowornotshowJava
elementsinfiles.UsetheShowMembersinPackageExplorercheckboxonthe Java>Appearancepreferencepagetosetyourpreference.
4. SelecttheelementthatyouwanttocompareintheOutlineorthePackageExplorer.
5. Fromtheelement'spopupmenu,selectCompareWith>ElementfromLocalHistory.
6. TheHistoryviewopensandshowsalleditionsoftheselectedelementavailableinthelocalhistory.
7. Selectaneditioninthehistoryviewtoseethedifferencesbetweentheselectededitionandtheeditionintheworkbenchinacomparisoneditor.
8. Ifyouaredonewiththecomparison,clickclosethecomparisoneditor.
Javaviews
Javaeditor
Usingthelocalhistory
Javaoutline
4.3.2.ReplacingaJavaElementWithaLocalHistoryEdition
1. MakesurethataJavaviewisvisible.
2. OpenaJavaeditorfortheJavafileinwhichyouwanttoreplaceaJavaelementwithaneditionfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea.TheOutlineviewalsodisplaystheJavafile.Note:ThePackageExplorercanbeconfiguredtoshowornotshowJava
elementsinfiles.UsetheShowMembersinPackageExplorercheckboxonthe Java>Appearancepreferencepagetosetyourpreference.
4. SelecttheelementthatyouwanttoreplaceintheOutlineorthePackageExplorer.
5. Fromtheelement'spopupmenu,selectReplaceWith>ElementfromLocalHistory.
6. Intheupperpaneoftheresultingdialog,allavailableeditionsoftheselectedelementinthelocalhistoryaredisplayed.
7. Selectaneditionintheupperpanetoviewthedifferencesbetweentheselectededitionandtheeditionintheworkbench.
8. WhenyouhaveidentifiedtheeditionwithwhichyouwanttoreplacetheexistingJavaelement,clickReplace.
9. Thelocalhistoryeditionreplacesthecurrentoneintheeditor.Note:Thechangedcompilationunithasnotyetbeensavedatthispoint.
Javaviews
Javaeditor
Usingthelocalhistory
Javaoutline
4.3.3.RestoringaDeletedWorkbenchElement
1. EnsurethataJavaviewthatshowJavaelementsinsidefiles(suchastheOutlineview)isvisible.
2. OpenthecompilationunittowhichyouwanttoaddapreviouslyremovedJavaelementfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea,andtheJavaviewshowsthecontentoftheJavafile.
4. IntheJavaview,selecttheelementtowhosecontainertypeyouwanttorestorethedeletedelement.
5. Fromthetype'spopupmenuintheJavaview,selectRestorefromLocalHistory.
6. Intheupperleftpaneoftheresultingdialog,allavailableeditionsoftheselectedelementinthelocalhistoryaredisplayed.
7. Intheleftpanecheckallelementsthatyouwanttoreplace.
8. Foreverycheckedelementselectaneditionintherighthandpaneandviewitscontentinthebottompane.
9. Whenyouhaveidentifiedtheeditionthatyouwanttorestore,pressRestore.Thelocalhistoryeditionsareloadedintotheeditor.
Javaeditor
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 104/322
12/10/2015 Javadevelopmentuserguide
Usingthelocalhistory
Javaoutline
4.4.ExternalizingStrings
Contents
Findingstringstoexternalize
Findingunusedandincorrectlyusedkeysinpropertyfiles
4.4.1.FindingStringstoExternalize
Tofindstringstoexternalize:
InaJavaview(e.g.PackageExplorer),selectasetofpackages,sourcefoldersorprojects.
Fromthemenubar,selectSource>ExternalizeStrings...
Adialogcomesupwithalistofallcompilationunitsthathavesomenonexternalizedstrings
Inthedialog,youcandoubleclickonalistedcompilationunitorpresstheExternalizebuttontoopentheExternalizeStringswizard
Stringexternalization
Findingunusedandincorrectlyusedkeysinpropertyfiles
Externalizestringswizard
Sourcemenu
4.4.2.FindingUnusedandIncorrectlyUsedKeysinPropertyFiles
Findingunusedandincorrectlyusedkeysinapropertyfile:
inaJavaview(e.g.PackageExplorer),selectasetofpackages,sourcefolders,projects,messagepropertyfiles,orresourcebundleaccessorclasses
fromthemenubar,selectSource>FindBrokenExternalizedStrings
Afterthesearchisfinished,theSearchResultviewdisplaysalistofunusedkeysinthepropertiesfilesandallincorrectreferencestononexistingkeys.
Stringexternalization
Externalizingstrings
Findingstringstoexternalize
Externalizestringswizard
Sourcemenu
4.5.1.OpeninganEditorforaSelectedElement
Youcanselectthenameofatype,method,orfieldintheJavasourceeditororinthescrapbookandopenaneditoronthedefinitionoftheelement.
1. IntheJavaeditor,selectthenameofatype,method,orfield.Youcanalsojustclickintothenameonce.
2. Dooneofthefollowing:
Fromthemenubar,selectNavigate>OpenDeclaration
Fromtheeditor'spopupmenu,selectOpenDeclaration
PressF3
or
1. HolddowntheCtrlkey.
2. IntheJavaeditor,movethemouseoverthenameofatype,method,orfielduntilthenamebecomesunderlined.
3. Clickthehyperlinkonce.
Iftherearemultipledefinitionsofthesamename,adialogisshown,andyoucanselectonedefinitionthatyouwanttoopen.Aneditoropenscontainingtheselectedelement.
Javaeditor
Navigatemenu
Viewsandeditors
4.5.2.ShowinganElementinthePackageExplorerView
Youcanrevealanelement'slocationinthePackageExplorerview
SelectaJavaelementoractivateaJavaeditor.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 105/322
12/10/2015 Javadevelopmentuserguide
Fromthemenubar,selectNavigate>ShowIn>PackageExplorer.IfthePackageExplorerisnotalreadyopen,thenitopensinthecurrentperspective.Theworkbench
navigatestotheselectedelement(ortheeditedcompilationunit).
FromtheJavaeditor'spopupmenu,selectShowIn>PackageExplorer.Thecurrentlyeditedcompilationunitwillberevealed.
Note:TheelementmightnotberevealedifPackageExplorerfiltersareactiveortheShowMembersinPackageExplorerpreferenceisclearedonthe Java>Appearance
preferencepage.
Javaviews
Settingexecutionarguments
Javapreferencepage
PackageExplorer
4.5.3.OpeningaTypeinthePackageExplorerView
YoucanopenthePackageExploreronanytypethatisincludedonaproject'sclasspath.
1. Fromthemenubar,selectNavigate>GoTo>Type.TheGotoTypedialogopens.
2. IntheChooseatypefield,begintypinganexpressiontonarrowthelistofavailabletypes,usingwildcardsasneeded.Asyoutype,thelistisfilteredtodisplayonlytypes
thatmatchthecurrentexpression.
3. IntheMatchingitemslist,selectatype.Hint:youcanpresstheDownkeytomovetothefirsttype.
4. ClickOKwhenyouaredone.TheselectedtypeisdisplayedinthePackageExplorer.
Note:TheGotoTypedialogmaintainsahistoryofrecentlyopenedtypes.Theseareshownwhenthedialogisopenedandstayaboveaseparatorlinewhenyoustarttotypeafilter
expression.
Note:RevealingmaynotbepossibleifPackageExplorerfiltersareapplied.
Javadevelopmenttools(JDT)
Showingatype'scompilationunitinthePackageExplorer
Navigateactions
PackageExplorer
4.5.4.OpeninganEditoronaType
Youcanopenaneditoronanytypeintheworkbench.
1. PressCtrl+Shift+Tor,selectNavigate>OpenTypefromthemenubar.TheOpenTypedialogopens.
2. IntheEntertypenameprefixorpatternfield,begintypinganexpressiontonarrowthelistofavailabletypes,usingwildcardsasneeded.Asyoutype,thelistisfilteredto
displayonlytypesthatmatchthecurrentexpression.CamelCasenotationisalsosupportedthatmeansyouonlyneedtoenterthecapitallettersofthetypename.
3. IntheMatchingitemslist,selectatype.Hint:youcanpresstheDownkeytomovetothefirsttype.
4. ClickOKwhenyouaredone.Aneditoropensontheselectedtype.
Note:TheOpenTypedialogmaintainsahistoryofrecentlyopenedtypes.Theseareshownwhenthedialogisopenedandstayaboveaseparatorlinewhenyoustarttotypeafilter
expression.
Note:IfyouopenatypefromaCLASSorJARfile,youwillseeaspecialeditorshowingonlymethodsignaturesunlessyouhaveattachedsourcetoit.
Javaeditor
Openinganeditorforaselectedelement
Opentypedialog
Navigateactions
Viewsandeditors
4.5.5.OpeningaPackage
TorevealapackageinthetreeofthePackageExplorer:
1. SelectNavigate>GoTo>Packagefromthemenubar.TheGotoPackagedialogopens.
2. TypeapackagenameintheChooseapackagefieldtonarrowthelistofavailablepackages,usingwildcardsasneeded.Asyoutype,thelistisfilteredtodisplayonly
packagesthatmatchthecurrentexpression.
3. Selectapackagefromthelist,thenclickOK.TheselectedpackageisdisplayedinthePackageExplorer.
Javaviews
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 106/322
12/10/2015 Javadevelopmentuserguide
Navigateactions
PackageExplorer
4.6.WorkingwithJREs
YoucaninstallasmanydifferentJavaRuntimeEnvironments(JREs)asyoulike.JREsareusedtorunanddebugjavaprograms.YourJREsaremanagedontheInstalledJREs
preferencepage.
AJREdefinitionconsistsof:
ThetypeoftheJRE(e.g.StandardVMorStandard1.x.xVM)
Aname
ThelocationwheretheJREisinstalled
ThesystemlibrariescontainingtheJavasystemclasses(likejava.lang.Object).Optionally,thesystemlibrariescanbeassociatedwith:
thesourcefilecontainingthesourcefortheclassesintheJRE'sCLASSfiles
ajavadoclocation(URL)
externalannotations.
OtherinformationneededbytheVMtobuild,runanddebugapplications.
YoucanswitchthedefaultJREfortheworkbench.ThedefaultJREisusedbydefaultwhenbuilding,running,anddebuggingapplications.Alternatively,projectsmayspecifya
specificJREthattheyshouldbebuiltandrunwith.
Javadevelopmenttools(JDT)
AddinganewJREdefinition
DeletingaJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject
InstalledJREspreferencepage
4.6.1.AssigningthedefaultJREfortheworkbench
ThedefaultJREisusedforcompilingandlaunchingJavaprogramsinallprojectsunlessyouspecificallyoverridethedefaultJREonaproject'sbuildpathoronalaunch
configuration.
HereishowyoucanchangethedefaultJRE:
1. Openthe Java>InstalledJREspreferencepage.
2. ChecktheboxonthelinefortheJREthatyouwanttoassignasthedefaultJREinyourworkbench.IftheJREyouwanttoassignasthedefaultdoesnotappearinthelist,
youmustaddit.
3. ClickOK.
Note:ChangingthedefaultJREmaycauseabuildtooccurifyouhaveautobuildenabled(Project>BuildAutomaticallyorinthe General>Workspacepreferencepage).
Javadevelopmenttools(JDT)
WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
ChoosingaJREforlaunchingaproject
InstalledJREspreferencepage
4.6.2.AddinganewJREdefinition
InyourworkspaceyoucanhaveanynumberofJREdefinitions.YoucanalsoaddasmanyJREdefinitionsasyouwant.
ToaddanewJREdefinition:
1. Openthe Java>InstalledJREspreferencepage.
2. SelecttheAdd...button.TheAddJREwizardopens.
3. YouwillhavetoselectthetypeofJREyouwouldliketocreate:
StandardVMYouwillselectafolderwheretheJREisinstalled.ThedetailsoftheJREwillbedeterminedbyscanningthelocation.Youcanfurthercustomizethe
JREinstall,specifyingvmarguments,sourceattachments,etc.
StandardVM1.x.xSameoptionsasastandardVMinstall,buttheinstalliscustomizedtohandlethe1.x.xinstall
ExecutionEnvironmentDescriptionYouwillselectanexecutionenvironment(EE)filethatdescribesallthedetailsrequiredtosetuptheJRE.Youwillbeableto
customizesomeaspectsoftheinstall.
StandardVM:
1. IntheJREhomefield,clickBrowse...toselectapathtotherootdirectoryofaJREinstallation(usuallythedirectorycontainingthebinandlibdirectoriesfortheJRE).You
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 107/322
12/10/2015 Javadevelopmentuserguide
mayalsotypeafoldernameintothisfield.
2. IntheJREnamefield,typeanameforthenewJREdefinition.AllJREsofthesametypemusthaveauniquename.
3. IntheDefaultVMArgumentsfield,youcanadd/editthedefaultargumentsthatwillbepassedtotheVMwhenlaunching.
4. ThedefaultlibrariesappearfortheJREintheJREsystemlibrarieslist.Youcanmodifythelibrariesasdesired.
SourceandjavadoclocationscanbespecifiedforthereferencedJARs.TheJavadoclocationisusedbytheJavadocexportwizardasadefaultvalueandbythe'Open
ExternalJavadoc'action.
Jarscanbeadded,removed,andreordered.
5. ClickFinishwhenyouaredone.
Standard1.1.xVM:
FollowthesamestepsasforStandardVMJREs.
ExecutionEnvironmentFiles:
FormoreinformationonEEFilestructureseetheWikiPage.
1. IntheDefinitionhomedirectoryfield,clickFile...toselectaexecutionenvironmentdescriptionfiletoloadtheJREinstallationfrom.Youmayalsotypeafilepathintothis
field.
2. IntheJREnamefield,typeanameforthenewJREdefinition.AllJREsofthesametypemusthaveauniquename.
3. IntheDefaultVMArgumentsfield,youcanadd/editthedefaultargumentsthatwillbepassedtotheVMwhenlaunching.
4. ThedefaultlibrariesappearfortheJREintheJREsystemlibrarieslist.Youcanmodifythelibrariesasdesired.
SourceandjavadoclocationscanbespecifiedforthereferencedJARs.TheJavadoclocationisusedbytheJavadocexportwizardasadefaultvalueandbythe'Open
ExternalJavadoc'action.
Jarscanbeadded,removed,andreordered.
5. ClickFinishwhenyouaredone.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 108/322
12/10/2015 Javadevelopmentuserguide
Javadevelopmenttools(JDT)
WorkingwithJREs
DeletingaJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject
InstalledJREspreferencepage
4.6.3.ChoosingaJREforalaunchconfiguration
InsteadofusingthedefaultJREforrunninganddebuggingallJavaApplicationlaunchconfigurations,youcanspecificallyassignaJREforlaunchinganindividualconfiguration.
1. WithaJavaApplicationconfigurationselectedinthe LaunchConfigurationDialog,selecttheJREtab.
2. InthelistofavailableJREs,selecttheJREyouwanttousetolaunchthisconfigurationandclickApply,thenRunorDebug.
Note:ChangingtheJREusedforrunningdoesnotaffectthewayJavasourceiscompiled.Youcanadjustthebuildpathtocompileagainstcustomlibraries.
Javadevelopmenttools(JDT)
WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
ChoosingadefaultJRE
InstalledJREspreferencepage
4.6.4.DeletingaJREdefinition
YoucandeleteJavaruntimeenvironmentdefinitionsthatareavailableforexecutingJavaprogramsintheworkbench.
1. Openthe Java>InstalledJREspreferencepage.
2. SelectthedefinitionyouwanttodeleteandclickRemove.
3. ChecktheboxforthedefinitionthatyouwanttouseasthedefaultJREfortheworkbench.
Javadevelopmenttools(JDT)
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 109/322
12/10/2015 Javadevelopmentuserguide
WorkingwithJREs
AddinganewJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject
InstalledJREspreferencepage
4.7.RunningandDebugging
YoumaylaunchyourJavaprogramsfromtheworkbench.Theprogramsmaybelaunchedineitherrunordebugmode.
Inrunmode,theprogramexecutes,buttheexecutionmaynotbesuspendedorexamined.
Indebugmode,executionmaybesuspendedandresumed,variablesmaybeinspected,andexpressionsmaybeevaluated.
Debugger
Remotedebugging
Localdebugging
Changingdebuggerlaunchoptions
ChoosingaJREforlaunchingaproject
CreatingaJavascrapbookpage
DisconnectingfromaVM
LaunchingaJavaprogram
Localdebugging
Preparingtodebug
Relaunchingaprogram
Remotedebugging
Resumingtheexecutionofsuspendedthreads
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram
Suspendingthreads
RunMenu
Debugview
DebugPreferences
ConsolePreferences
4.7.1.1.AddingLineBreakpoints
Linebreakpointsaresetonanexecutablelineofaprogram.
1. Intheeditorarea,openthefilewhereyouwanttoaddthebreakpoint.
2. Directlytotheleftofthelinewhereyouwanttoaddthebreakpoint,openthemarkerbar(verticalruler)popupmenuandselectToggleBreakpoint.Youcanalsodouble
clickonthemarkerbarnexttothesourcecodeline.Anewbreakpointmarkerappearsonthemarkerbar,directlytotheleftofthelinewhereyouaddedthebreakpoint.
Also,thenewbreakpointappearsintheBreakpointsViewlist.
Whilethebreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecuted.Thedebuggerselectsthethreadthathassuspendedanddisplaysthethread'sstack
frames.ThelinewherethebreakpointwassetishighlightedintheeditorintheDebugPerspective.
Debugger
Javaperspectives
Javaeditor
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram
Breakpointsview
4.7.1.2.RemovingLineBreakpoints
Breakpointscanbeeasilyremovedwhenyounolongerneedthem.
1. Intheeditorarea,openthefilewhereyouwanttoremovethebreakpoint.
2. Directlytotheleftofthelinewhereyouwanttoremovethebreakpoint,openthemarkerbarpopupmenuandselectToggleBreakpoint.Thebreakpointisremovedfromthe
workbench.Youcanalsodoubleclickdirectlyonthebreakpointicontoremoveit.
BreakpointscanalsoberemovedintheBreakpointsView.Selectthebreakpoint(s)toberemovedandfromthecontextmenuselectRemove.
AllbreakpointscanberemovedfromtheworkbenchusingtheRemoveAllactioninthecontextmenuoftheBreakpointsView.
Ifyoufindyourselffrequentlyaddingandremovingabreakpointinthesameplace,considerdisablingthebreakpointwhenyoudon'tneedit(usingDisableBreakpointinthe
breakpointcontextmenuortheBreakpointsView)andenablingitwhenneededagain.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 110/322
12/10/2015 Javadevelopmentuserguide
Debugger
Javaperspectives
Javaeditor
Addingbreakpoints
Enablinganddisablingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Managingconditionalbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram
Breakpointsview
4.7.1.3.Enablinganddisablingbreakpoints
Breakpointscanbeenabledanddisabledasneeded.Whenabreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecuted.Whenabreakpointisdisabled,
threadexecutionisnotsuspendedbythepresenceofthebreakpoint.
TodisableabreakpointintheBreakpointsView:
1. Openthebreakpoint'scontextmenuandselectDisable,ordeselectthebreakpoint'scheckbox.
2. Thebreakpointimagewillchangetoawhitecircleanditscheckboxwillbeempty.
Todisableabreakpointinthemarkerbarofaneditor:
1. Openthebreakpoint'scontextmenuandselectDisableBreakpoint.
2. Thebreakpointimagewillchangetoawhitecircle.
ToenablethebreakpointintheBreakpointsView:
1. Openthebreakpoint'scontextmenuandselectEnable,orselectthebreakpoint'scheckbox.
2. Thebreakpointimagewillchangebacktoabluecircle,anditscheckboxwillbechecked.
Toenableabreakpointinthemarkerbarofaneditor:
1. Openthebreakpoint'scontextmenuandselectEnableBreakpoint.
2. Thebreakpointimagewillchangetoawhitecircle.
Debugger
Javaperspectives
Javaeditor
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Settingmethodbreakpoints
Managingconditionalbreakpoints
Steppingthroughtheexecutionofaprogram
Breakpointsview
4.7.1.4.SettingMethodBreakpoints
Methodbreakpointsareusedwhenworkingwithtypesthathavenosourcecode(binarytypes).
1. OpentheclassintheOutlineView,andselectthemethodwhereyouwanttoaddamethodbreakpoint.
2. Fromthemethod'spopupmenu,selectToggleMethodBreakpoint.
3. AbreakpointappearsintheBreakpointsView.Ifsourceexistsfortheclass,thenabreakpointalsoappearsinthemarkerbarinthefile'seditorforthemethodthatwas
selected.
4. Whilethebreakpointisenabled,threadexecutionsuspendswhenthemethodisentered,beforeanylineinthemethodisexecuted.
Methodbreakpointscanalsobesetuptobreakonmethodexit.IntheBreakpointsview,selectthebreakpointandtoggletheExititeminitscontextmenu.
Methodbreakpointscanberemoved,enabled,anddisabledjustlikelinebreakpoints.
Breakpoints
Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Breakpointsview
Javaoutline
4.7.1.5.ApplyingHitCounts
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 111/322
12/10/2015 Javadevelopmentuserguide
Ahitcountcanbeappliedtolinebreakpoints,exceptionbreakpoints,watchpointsandmethodbreakpoints.Whenahitcountisappliedtoabreakpoint,thebreakpointsuspends
executionofathreadthenthtimeitishit,butneveragain,untilitisreenabledorthehitcountischangedordisabled.
Tosetahitcountonabreakpoint:
1. Selectthebreakpointtowhichahitcountistobeadded.
2. Fromthebreakpoint'spopupmenu,selectHitCount.
3. IntheEnterthenewhitcountforthebreakpointfield,typethenumberoftimesyouwanttohitthebreakpointbeforesuspendingexecution.
Note:Whenthebreakpointishitforthenthtime,thethreadthathitthebreakpointsuspends.Thebreakpointisdisableduntileitheritisreenabledoritshitcountischanged.
Breakpoints
Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Settingmethodbreakpoints
Breakpointsview
4.7.1.6.Managingconditionalbreakpoints
Aconditionalexpressioncanbeappliedtoalinebreakpointsuchthatthebreakpointsuspendsexecutionofathreadinoneofthesecases:
whentheresultoftheexpressionistrue
whentheresultoftheexpressionchanges
AconditionalexpressioncancontainarbitraryJavacodeandmaycontainmorethanonestatement,allowingbreakpointconditionstoimplementfeaturesliketracing.Forexample,a
conditioncanexecuteaprintstatementandthenreturnahardcodedvaluetoneversuspend("System.out.println(...)returnfalse").
Tosetaconditiononabreakpoint:
1. Findthebreakpointtowhichanenablingconditionistobeapplied(intheBreakpointsVieworintheeditormarkerbar).
2. Fromthebreakpoint'spopupmenu,selectBreakpointProperties....TheBreakpointpropertiesdialogwillopen.
3. Inthepropertiesdialog,checktheEnableConditioncheckbox.
4. IntheConditionfieldentertheexpressionforthebreakpointcondition.
5. Dooneofthefollowing:
Ifyouwantthebreakpointtostopeverytimetheconditionevaluatestotrue,selecttheconditionis'true'option.Theexpressionprovidedmustbeaboolean
expression.
Ifyouwantthebreakpointtostoponlywhentheresultoftheconditionchanges,selectthevalueofconditionchangesoption.
6. SelectOKtoclosethedialogandcommitthechanges.Whilethebreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecutedifthebreakpoint
conditionevaluatestotrue.
Aconditionalbreakpointhasaquestionmarkoverlayonthebreakpointicon.
Debugger
Javaperspectives
Javaeditor
Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram
Breakpointsview
4.7.1.7.CatchingJavaExceptions
Itispossibletosuspendtheexecutionofthreadwhenanexceptionisthrownbyspecifyinganexceptionbreakpoint.Executioncanbesuspendedatlocationswheretheexceptionis
uncaught,caught,orboth.
1. ChooseAddJavaExceptionBreakpointfromtheBreakpointsViewortheworkbenchRunmenu.
2. Adialoglistingalloftheavailableexceptionsispresented(seethefollowingfigure).
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 112/322
12/10/2015 Javadevelopmentuserguide
3. Typethenameoftheexceptionyouwanttocatchorselectitfromthelist.
4. Atthebottomofthepage,usethecheckboxestospecifyhowyouwantexecutiontosuspendatlocationswheretheexceptionisthrown.
SelectCaughtifyouwantexecutiontosuspendatlocationswheretheexceptionisthrownandcaughtbyacatchclause.
SelectUncaughtifyouwantexecutiontosuspendatlocationswheretheexceptionisuncaught.
Note:Exceptionbreakpointscanbeenabledanddisabledandhavehitcountsjustlikeregularbreakpoints.
Javadevelopmenttools(JDT)
Breakpoints
CreatingExceptionBreakpointFilters
Suspendingthreads
Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Settingmethodbreakpoints
Breakpointsview
AddJavaexceptionbreakpoint
4.7.1.8.CreateExceptionBreakpointFiltering
TypenameandpackagenamefilteringcanbesetupforJavaexceptionbreakpoints.Thiscanbedonefromanexceptionbreakpoints'Filteringpropertiespage,asshowninthe
followingfigure.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 113/322
12/10/2015 Javadevelopmentuserguide
UsingtheFilteringpropertiespagetherearefourwaystoaddfilteringforaJavaexceptionbreakpoint:
1. Youcanselectspecificthreadstorestrictthebreakpointto(whichmustbedonewhileinadebugsession)
2. YoucanusetheAddClassbuttontoselectaclassviatheTypeSelectionDialog
3. YoucanusetheAddPackagebuttontoselectapackageusingafilteredTypeSelectionDialog
4. YoucanusetheAddbuttontodefineyourownpatterntomatchasaclassand/orpackagefilter
DefiningYourOwnFilterPattern
UsingtheAddbuttonmentionedabove,youcandefineyourownpatterntobeusedasafilterforaJavaexceptionbreakpoint.Oncepressed,youcanthen
enteranyexpressioninthenewspaceintheSelectedLocationslist,asshowninthefollowingfigure.
Therearesomerulestofollowwhencreatingyourownpattern.
1. Yourpatterncanonlycontaina'*'attheend
2. Yourpatternmustbefullyqualified,E.g.a.b.c.MyClass
3. Yourpatterncannothavespacesinit
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 114/322
12/10/2015 Javadevelopmentuserguide
Examples
a.b.c*wouldmatcheverythinginthepackagea.b.c
a.b.c.My*wouldmatchanythinginthea.b.cpackagethatstartedwith'My'
My*wouldmatchanythinginthedefaultpackagethatstartedwith'My'
4.7.2.1.PreparingtoDebug
Youcanmakeyourprogramseasiertodebugbyfollowingtheseguidelines:
Wherepossible,donotputmultiplestatementsonasingleline,becausesomedebuggerfeaturesoperateonalinebasis.Forexample,youcannotstepoverorsetline
breakpointsonmorethanonestatementonthesameline.
AttachsourcecodetoJARfilesifyouhavethesourcecode.
Debugger
Remotedebugging
Localdebugging
Changingdebuggerlaunchoptions
Runninganddebugging
Debugpreferences
Debugview
RunMenu
4.7.2.2.LaunchingaJavaprogramindebugmode
Launchingaprogramindebugmodeallowsyoutosuspendandresumetheprogram,inspectvariables,andevaluateexpressionsusingthedebugger.
TolaunchaJavaprogramindebugmode,
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilewiththemainmethodyouwanttolaunch.
2. PresstheDebug[ ]buttonintheworkbenchtoolbarorselectRun>Debugfromtheworkbenchmenubar.AlternativelyyoucanselectRun>DebugAs>Java
Applicationfromtheworkbenchmenubar,orselectDebugAs>JavaApplicationinthePackageExplorerpopupmenuorinthedropdownmenuontheDebugtoolbar
button.
3. YourprogramisnowlaunchedandthelaunchedprocessappearsintheDebugview.
Ifyouwantyourprogramtostopinthemainmethodsothatyoucanstepthroughitscompleteexecution,createaJavaApplicationlaunchconfigurationandchecktheStopin
maincheckboxontheMaintab.
YoucanalsodebugaJavaprogrambyselectingaprojectinsteadofthecompilationunitorclassfile.Youwillbepromptedtoselectaclassfromthoseclassesthatdefineamain
method.(Ifonlyoneclasswithamainmethodisfoundintheproject,thatclassislaunchedasifyouselectedit.)
Javaviews
Javaeditor
Debugger
ConnectingtoaremoteVMwiththeJavaRemoteApplicationlauncher
Relaunchingaprogram
Runninganddebugging
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram
Debugview
PackageExplorer
4.7.2.3.SuspendingThreads
Tosuspendanexecutingthread:
1. SelectthethreadintheDebugView.
2. ClicktheSuspendbutton[ ]intheviewtoolbar.
Thethreadsuspendsitsexecution.Thecurrentcallstackforthethreadisdisplayed,andthecurrentlineofexecutionishighlightedintheeditorintheDebugPerspective.
Whenathreadsuspends,thetopstackframeofthethreadisautomaticallyselected.TheVariablesViewshowsthestackframe'svariablesandtheirvalues.Complexvariables
canbefurtherexaminedbyexpandingthemtoshowthevaluesoftheirmembers.
WhenathreadissuspendedandthecursorishoveredoveravariableintheJavaeditor,thevalueofthatvariableisdisplayed.
Debugger
Javaeditor
Javaperspectives
CatchingJavaexceptions
Evaluatingexpressions
Resumingtheexecutionofsuspendedthreads
Steppingthroughtheexecutionofaprogram
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 115/322
12/10/2015 Javadevelopmentuserguide
Debugview
Resumecommand
Suspendcommand
Variablesview
4.7.2.4.Resumingtheexecutionofsuspendedthreads
Toresumetheexecutionofasuspendedthreads:
1. SelectthethreadoritsstackframeintheDebugView.
2. ClicktheResumebutton[ ]intheviewtoolbar(orpresstheF8key).
Thethreadresumesitsexecutionandstackframesarenolongerdisplayedforthethread.TheVariablesViewisalsocleared.
Debugger
Evaluatingexpressions
Steppingthroughtheexecutionofaprogram
Suspendingthreads
Debugview
Resumecommand
Suspendcommand
VariablesView
4.7.2.5.SteppingthroughtheexecutionofaJavaprogram
Whenathreadissuspended,thestepcontrolscanbeusedtostepthroughtheexecutionoftheprogramlinebyline.Ifabreakpointisencounteredwhileperformingastep
operation,theexecutionwillsuspendatthebreakpointandthestepoperationisended.
Stepover
1. SelectastackframeintheDebugView.ThecurrentlineofexecutioninthatstackframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepOverbutton[ ]intheviewtoolbar,orpresstheF6key.Thecurrentlyselectedlineisexecutedandsuspendsonthenextexecutableline.
Stepinto
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepIntobutton[ ]intheviewtoolbar,orpresstheF5key.Thenextexpressiononthecurrentlyselectedlinetobeexecutedisinvoked,andexecution
suspendsatthenextexecutablelineinthemethodthatisinvoked.
StepintoSelection
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. IntheJavaEditor,withinthecurrentlineofexecution,placethecursoronthenameofamethodthatyouwouldliketostepinto.
3. ClicktheStepintoSelectionactionintheRunmenuorJavaeditorcontextmenu,orpresstheCtrlF5key.Executionresumesuntiltheselectedmethodisinvoked.
Stepwithfilters
1. ToggletheUseStepFiltersbutton[ ]intheDebugviewtoolbar,oruseShift+F5.Whentheactionistoggledon,eachofthestepactions(over,into,return)willapplythe
setofstepfilterswhicharedefinedinthe Java>Debug>StepFilteringpreferencepage.Whenastepactionisinvoked,steppingwillcontinueuntilanunfilteredlocation
isreachedorabreakpointisencountered.
StepReturn
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepReturnbutton[ ]intheviewtoolbarorpresstheF7key.Executionresumesuntilthenextreturnstatementinthecurrentmethodisexecuted,and
executionsuspendsonthenextexecutableline.
Runtoline
Whenathreadissuspended,itispossibletoresumeexecutionuntilaspecifiedlineisexecuted.Thisisaconvenientwaytosuspendexecutionatalinewithoutsettinga
breakpoint.
1. Placeyourcursoronthelineatwhichyouwanttheprogramtorun.
2. SelecttheRuntoLinecommand[ ]fromthepopupmenuoruseCtrl+R.Programexecutionisresumedandsuspendsjustbeforethespecifiedlineistobeexecuted.
Itispossiblethatthelinewillneverbehitandthattheprogramwillnotsuspend.
Breakpointsandexceptionscancausethethreadtosuspendbeforereachingthespecifiedline.
Breakpoints
Javaperspectives
Addingbreakpoints
LaunchingaJavaprogram
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 116/322
12/10/2015 Javadevelopmentuserguide
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Settingexecutionarguments
Suspendingthreads
Debugview
4.7.2.6.Inspectingvalues
Whenastackframeisselected,youcanseethevisiblevariablesinthatstackframeintheVariablesView.
TheVariablesviewshowsthevalueofprimitivetypes.Complexvariablescanbeexaminedbyexpandingthemtoshowtheirmembers.
InspectingValuesintheExpressionsView
InspectingValuesintheVariablesView
InspectingValuesinotherviews
4.7.2.7.Evaluatingexpressions
WhentheVMsuspendsathread(duetohittingabreakpointorsteppingthroughcode),youcanevaluateexpressionsinthecontextofastackframe.
1. Selectthestackframeinwhichanevaluationistobeperformed.Theevaluationcontextwillbethecurrentlyselectedvariableintheview.Ifnovariableisselected,the
selectedstackframewillbethecontext.
2. Expressionscanbeenteredandevaluatedinthefollowingareas:
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
JavaEditorwhenitisdisplayingsourceanditisnotreadonly
3. SelecttheexpressiontobeevaluatedandselectDisplay,InspectorExecutefromthecontextpopupmenu.TheresultofaDisplayorInspectevaluationisshownina
popupwindow.NotethatExecutedoesnotdisplayaresulttheexpressionisjustexecuted.
4. TheresultpopupwindowcanbedismissedbyclickingoutsideofthepopupwindoworbypressingEsc.TheresultcanbepersistedtotheDisplayview(ifDisplaywas
chosen)orExpressionsview(ifInspectwaschosen)bypressingthekeysequenceshownatthebottomofthepopupwindow.Forexample,tomovetheresultofanInspect
evaluationtotheExpressionsviewpressCtrlShiftI.NotethatwhentheDisplayactionisusedfromtheDisplayviewtheresultiswrittentotheDisplayviewratherthana
popup
Note:Evaluationscannotbeperformedinthreadsthathavebeenmanuallysuspended.
Debugger
Javaeditor
Suspendingthreads
Resumingtheexecutionofsuspendedthreads
DetailPane
Displayview
Expressionsview
Variablesview
4.7.3.1.UsingtheremoteJavaapplicationlaunchconfiguration
TheRemoteJavaApplicationlaunchconfigurationshouldbeusedwhendebugginganapplicationthatisrunningonaremoteVM.Sincetheapplicationisstartedontheremote
system,thelaunchconfigurationdoesnotspecifytheusualinformationabouttheJRE,programarguments,orVMarguments.Instead,informationaboutconnectingtothe
applicationissupplied.
TocreateaRemoteJavaApplicationlaunchconfiguration,dothefollowing:
1. Select Run>DebugConfigurations...fromtheworkbenchmenubar(orDebugConfigurations...fromthedropdownmenuontheDebugtoolbarbutton)toshowthe
launchconfigurationdialog.
2. SelecttheRemoteJavaApplicationinthelistofconfigurationtypesontheleft.
3. ClicktheNewtoolbarbutton.Anewremotelaunchconfigurationiscreatedandthreetabsareshown:Connect,Source,andCommon.
4. IntheProjectfieldoftheConnecttab,typeorbrowsetoselecttheprojecttouseasareferenceforthelaunch(forsourcelookup).Aprojectdoesnotneedtobespecified.
5. TheConnectionTypefieldoftheConnecttaballowsyoutochoosehowyouwillconnecttothevirtualmachine.Inmostcases,youwillbeattachingtothevmataspecific
location,inwhichcaseselectStandard(SocketAttach).therestoftheseinstructionsassumeyouhavechosenthisoption.TheStandard(SocketListen)connectiontype
createsalaunchthatwilllistenforincomingconnectionsfromaremoteVM.Youwillneedtospecifyaportthatthelaunchwilllistenat.
6. IntheHostfieldoftheConnecttab,typetheIPaddressordomainnameofthehostwheretheJavaprogramisrunning.
Iftheprogramisrunningonthesamemachineastheworkbench,typelocalhost.
7. InthePortfieldoftheConnecttab,typetheportwheretheremoteVMisacceptingconnections.Generally,thisportisspecifiedwhentheremoteVMislaunched.
8. TheAllowterminationofremoteVMflagisatogglethatdetermineswhethertheTerminatecommandisenabledinthedebugger.Selectthisoptionifyouwanttobeableto
terminatetheVMtowhichyouareconnecting.
9. ClickDebug.ThelaunchattemptstoconnecttoaVMatthespecifiedaddressandport,andtheresultisdisplayedintheDebugview.Ifthelauncherisunabletoconnectto
aVMatthespecifiedaddress,anerrormessageappears.
SpecificinstructionsforsettinguptheremoteVMshouldbeobtainedfromyourVMprovider.
Debugger
RemoteDebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 117/322
12/10/2015 Javadevelopmentuserguide
LaunchingaJavaprogram
DisconnectingfromaVM
Settingexecutionarguments
Debugview
4.7.3.2.DisconnectingfromaVM
TodisconnectfromaVMthatwasconnectedtowithaRemoteJavaApplicationlaunchconfiguration:
1. IntheDebugView,selectthelaunch.
2. ClicktheDisconnectbutton[ ]intheviewtoolbar.
CommunicationwiththeVMisterminated,andallthreadsintheremoteVMareresumed.AlthoughtheremoteVMcontinuestoexecute,thedebugsessionisnowterminated.
Debugger
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
Runninganddebugging
Debugview
4.7.4.CreatingaJavaapplicationlaunchconfiguration
WhenyouchooseRun>RunAs>JavaApplicationtolaunchyourclass,youarerunningyourclassusingagenericJavaApplicationlaunchconfigurationthatderivesmostofthe
launchparametersfromyourJavaprojectandyourworkbenchpreferences.Insomecases,youwillwanttooverridethederivedparametersorspecifyadditionalarguments.
YoudothisbycreatingyourownJavaApplicationlaunchconfiguration.
1. Select Run>RunConfigurations...or Run>DebugConfigurations...fromtheworkbenchmenubar.Thisopensadialogthatletsyoucreate,modify,anddelete
launchconfigurationsofdifferenttypes.
2. SelectJavaApplicationinthelefthandlistoflaunchconfigurationtypes,andpresstheNewbuttoninthetoolbar.ThiswillcreateanewlaunchconfigurationforaJava
application.Thetabsontherighthandsideallowyoucontrolspecificaspectsofthelaunch.
TheMaintabdefinestheclasstobelaunched.Enterthenameoftheprojectcontainingtheclasstolaunchintheprojectfield,andthefullyqualifiednameofthe
mainclassintheMainclassfield.ChecktheStopinmaincheckboxifyouwanttheprogramtostopinthemainmethodwhenevertheprogramislaunchedin
debugmode.
Note:Youdonothavetospecifyaproject,butdoingsoallowsadefaultclasspath,sourcelookuppath,andJREtobechosen.
TheArgumentstabdefinestheargumentstobepassedtotheapplicationandtothevirtualmachine(ifany).Youcanalsospecifytheworkingdirectorytobe
usedbythelaunchedapplication.
TheJREtabdefinestheJREusedtorunordebugtheapplication.YoucanselectaJREfromthealreadydefinedJREs,ordefineanewJRE.
TheClasspathtabdefinesthelocationofclassfilesusedwhenrunningordebugginganapplication.Bydefault,theuserandbootstrapclasslocationsarederived
fromtheassociatedproject'sbuildpath.Youmayoverridethesesettingshere.
TheSourcetabdefinesthelocationofsourcefilesusedtodisplaysourcewhendebuggingaJavaapplication.Bydefault,thesesettingsarederivedfromthe
associatedproject'sbuildpath.Youmayoverridethesesettingshere.
TheEnvironmenttabdefinestheenvironmentvariablevaluestousewhenrunningordebuggingaJavaapplication.Bydefault,theenvironmentisinheritedfrom
theEclipseruntime.Youmayoverrideorappendtotheinheritedenvironment.Variablesspecifiedinthetabalwaysreplacevaluesintheunderlyingnative
environment.However,when"Appendenvironmenttonativeenvironment"isselectedthelaunchedenvironmentisseededwiththenativeenvironment,after
whichvariablesinthetabreplace(existingvariables)oraugmentthesetofenvironmentvariables.When"Replacenativeenvironmentwithspecifiedenvironment"
isselected,thelaunchedenvironmentiscomprisedonlyofthevariablesspecifiedinthetab.
TheCommontabdefinesgeneralinformationaboutthelaunchconfiguration.Youmaychoosetostorethelaunchconfigurationinaspecificfileandspecify
whichperspectivesbecomeactivewhenthelaunchconfigurationislaunched.
Debugger
Localdebugging
ChoosingaJREforlaunchingaproject
LaunchingaJavaprogram
Settingexecutionarguments
Changingdebuggerlaunchoptions
Debugpreferences
Debugview
RunMenu
4.7.5.LaunchingaJavaProgram
ThesimplestwaytolaunchaJavaprogramistorunitusingaJavaApplicationlaunchconfiguration.Thislaunchconfigurationtypeusesinformationderivedfromtheworkbench
preferencesandyourprogram'sJavaprojecttolaunchtheprogram.
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilewiththemainmethodyouwanttolaunch.
2. PresstheRun[ ]buttonintheworkbenchtoolbarorselectRun>Runfromtheworkbenchmenubar.Alternatively,selectRunAs>JavaApplicationinthePackage
Explorerpopupmenu,orselectRun>RunAs>JavaApplicationintheworkbenchmenubar,orselectRunAs>JavaApplicationinthedropdownmenuontheRun
toolbarbutton.
3. Yourprogramisnowlaunched,andtextoutputisshownintheConsoleView.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 118/322
12/10/2015 Javadevelopmentuserguide
YoucanalsolaunchaJavaprogrambyselectingaprojectinsteadofthecompilationunitorclassfile.Youwillbepromptedtoselectaclassfromthoseclassesthatdefineamain
method.(Ifonlyoneclasswithamainmethodisfoundintheproject,thatclassislaunchedasifyouselectedit.)
Javaviews
Javaeditor
Debugger
ConnectingtoaremoteVMwiththeJavaRemoteApplicationlauncher
Relaunchingaprogram
Runninganddebugging
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram
ConsoleView
Debugview
PackageExplorer
4.7.6.LaunchingaJavaapplet
IfyourJavaprogramisstructuredasanapplet,youcanusetheJavaAppletlaunchconfiguration.Thislaunchconfigurationusesinformationderivedfromtheworkbench
preferencesandyourprogram'sJavaprojecttolaunchtheprogram.
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilecontainingtheappletyouwanttolaunch.
2. PresstheRun[ ]buttonintheworkbenchtoolbarorselectRun>Runfromtheworkbenchmenu.Alternatively,selectRunAs>JavaAppletfromthePackage
Explorerpopupmenu,selectRun>RunAs>JavaAppletintheworkbenchmenubar,orselectRunAs>JavaAppletinthedropdownmenuontheRuntoolbar
button.
3. Yourprogramisnowlaunched.
YoucanalsolaunchaJavaappletbyselectingaprojectinsteadofthecompilationunitorclassfile.YouwillbepromptedtoselectaclassfromthoseclassesthatextendApplet.
(Ifonlyoneappletclassisfoundintheproject,thatclassislaunchedasifyouselectedit.)
Debugger
Relaunchingaprogram
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Debugview
PackageExplorer
4.7.7.Settingexecutionarguments
Ifyouwanttospecifyexecutionargumentsforyourprogram,youmustdefinealaunchconfigurationthatspecifiesthearguments.
1. Select Run>RunConfigurations...or Run>DebugConfigurations...fromtheworkbenchRunmenutoopenthelistoflaunchconfigurations.Launch
configurationsforJavaprogramsareshownunderneathJavaApplicationinthislist.
2. SelectanexistingconfigurationorcreateanewlaunchconfigurationbypushingtheNewbuttonafterselectingJavaApplication.
3. OntheArgumentstabfortheconfiguration,youcanspecifythefollowingfieldsasnecessary:
ProgramArguments:Applicationspecificvaluesthatyourcodeisexpecting(ausernameoraURLforlocatinghelpfiles,forexample).
VMArguments:ValuesmeanttochangethebehavioroftheJavavirtualmachine(VM).Forexample,youmayneedtotelltheVMwhethertouseajustintime(JIT)
compiler,oryoumayneedtospecifythemaximumheapsizetheVMshoulduse.RefertoyourVM'sdocumentationformoreinformationabouttheavailableVM
arguments.
WorkingDirectory:Theworkingdirectoryusedforthelaunchedprocess.Tochangefromusingthedefaultworkingdirectory,selectOtherandspecifytheworkspaceor
localdirectorytousefortheworkingdirectoryofthelaunchedprocess.
4. ClickApplyorClosewhenyouaredone.Everytimeyoulaunchthisconfiguration,theseexecutionargumentswillbeused.
CreatingaJavaApplicationlaunchconfiguration
LaunchingaJavaprogram
4.7.8.Relaunchingaprogram
Theworkbenchkeepsahistoryofeachlaunchedanddebuggedprogram.Torelaunchaprogram,dooneofthefollowing:
SelectapreviouslaunchfromRunorDebugbuttonpulldownmenus.
Fromthemenubar,selectRun>RunHistoryorRun>DebugHistoryandselectapreviouslaunchfromthesesubmenus.
IntheDebugView,selectaprocessthatyouwanttorelaunch,andselectRelaunchfromtheprocess'spopupmenu.
Torelaunch,dooneofthefollowing:
ClicktheRunorDebugbuttons(withoutusingthebuttonpulldownmenu).
SelectRun>RunLastLaunched(Ctrl+F11),orRun>DebugLastLaunched(F11)fromtheworkbenchmenubar.
PreferencecanbesetintheLaunchOperationsectionunderWindow>Preferences>Run/Debug>Launchingtolaunchpreviouslylaunchedapplicationoractiveeditor.
LaunchingaJavaprogram
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 119/322
12/10/2015 Javadevelopmentuserguide
Debugview
Relaunchcommand
TerminateandRelaunchcommand
4.7.9.InspectingmemoryintheMemoryview
WiththeMemoryview,youcanlookatthecontentsofmemoryataspecificaddress.Theaddresscanbeobtainedfromanexpressionthatreferencesavariableoraregister.When
youmonitormemory,youcansetthemonitortoberenderedinvariousdataformats.
TheMemoryviewiscomprisedoftwoportions:
TheMonitorspaneislocatedonthelefthandsideoftheview.Thisportionoftheviewcontainsalistofexpressions,variables,andregistersthatyouhaveaddedfor
monitoring.
TheRenderingspaneislocatedontherighthandsideoftheview(iftheviewissettohorizontalorientation).Youuseittosetthedataformat(orformats)thatyouwant
displayedformonitoredmemory.
WhenyoumonitoranaddressorexpressionfromtheMonitorspane,theRenderingspanebecomespopulatedwithasetofdefaultrenderingsprovidedbyyourdebugger.When
youmonitoranaddressorexpressionfromtheRenderingspane,thepanebecomespopulatedwithalistofrenderingsfromwhichyoucanchooseonetodisplay.
Youcanmonitormultiplevariables,expressions,andregistersintheMemoryviewandyoucanaddmultiplerenderingstotheRenderingspane.IntheMonitorspane,each
variable,expression,orregisterthatyouhaveaddedislisted.IntheRenderingspane,onlythememoryrendering(s)forthecurrentlyselectedmonitorintheMemoryviewis
displayed(multiplerenderingsareseparatedbytabsorasplitpane).
YoucansetthetwopanesintheMemoryviewtodisplayinahorizontalorientation(sidebyside)orinaverticalorientation(toptobottom).Tosetthelayoutoftheview,clickthe
MemoryviewdownarrowiconandselectLayoutfromthemenu.Thiswillopenasubmenu,fromwhichyoucanchoosetheorientationthatyouwanttodisplay.
4.7.9.1.Addingavariable,expression,orregistertotheMemoryview
Youcanaddaregister,variablename,orexpression(suchasarawaddress,forexample,0x00000234)toamemorymonitorfromtheMemoryview.
ToaddanewmemorymonitorfromtheMemoryview:
1. ClicktheMemoryviewAddMemoryMonitorpushbutton( ).ThisbuttonislocatedintheMonitorspane.
2. IntheMonitorMemorydialogbox,entertheaddressorexpressioninthefield(expressionsmustevaluatetoanaddress).Thisentrydoesnotneedtobecasesensitive.
Alternatively,ifyouhavepreviouslymonitoredtheaddressorexpressionwhendebuggingthisapplication,chooseitfromthepulldownlist.Dependingonthedebugengine
thatthedebuggeruserinterfaceisconnectedto,examplesofvalidexpressionsincluderegisternames,variables,andHEXaddresses.
Note:Whenaddingaregistertoamemorymonitor,theRegistersviewisaconvenientlocationtoseethenamesofallregistersinyourapplication.Youcanmakenoteofthe
nameofaregisterfromtheviewandthenuseitwhenaddingamemorymonitor.
3. ClickOK.
AfteraddingthenewmemorymonitoryoucanchoosethememoryformatthatyouwanttodisplayintheRenderingspane.
YoucanalsoaddanewmemorymonitorfromtheMemoryviewRenderingspane:
1. ClicktheMemoryviewAddRendering(s)pushbutton( ).ThisbuttonislocatedintheRenderingspane.
2. IntheAddMemoryRenderingdialogbox,selectanexistingmemorymonitorfromthepulldownlistoraddanewmemorymonitorbyclickingAddNew.Ifyouaddanew
memorymonitor,youwillbepromptedviatheMonitorMemorydialogboxtoenteranaddressorexpressiontomonitor.ClickOKtoreturntotheAddMemoryRenderingdialog
box.
3. Dooneofthefollowing:
SelectthememoryrenderingthatyouwanttodisplayforthememorymonitorandclickOK.
ClickCancelandthenchoosethememoryrenderingthatyouwanttodisplayrightfromtheRenderingspane.
4.7.9.2.Addingmultiplememoryrenderingsandremovingrenderings
Whenyouaddavariable,expression,orregistertotheMemoryview,youcandosomultipletimes,eachtimeaddinganew(orthesame)rendering.Alternatively,onceyouhave
addedamemorymonitorandrendering,youcangototheRenderingspaneandclicktheAddRendering(s)pushbutton( ).Thiswillpromptyouwithadialogtoselectthe
renderingthatyouwanttoaddtotheview.Inthisdialog,youcanselectmorethanonerenderingbyusingthekeyboardShiftorCtrlkeysdoingthiswillcausearenderingtobe
openedforeachrenderingformatthatisselected.Whenyouaddmultiplememoryrenderings,theyareseparatedbytabs.
YoucanalsosplittheMemoryRenderingspanebyselectingtheToggleSplitPanepushbutton( ).WhentheRenderingspaneissplit,youcanviewtworenderingssideby
side.
Whenyouhavemultiplememoryrenderingsforamemorymonitor,youcansettherenderingstobelinkedwithoneanother.Todothis,selecttheLinkMemoryRenderingPanes
pushbutton( ).Whenrenderingsarelinked,theyaresynchronizedwitheachother(forexample,ifyouchangethecolumnsizeinonerendering,thecolumnsizeintheother
renderingwillalsochangeorifyouscrollormovethecursorinonerendering,theotherrenderingwillscrollorfollowthesamecursormovement).Linkingmemoryrenderingsonly
appliestothecurrentMemoryview.IfyouhavemultipleMemoryviewsopen,theydonotlinktoeachother.
Toremovearendering,selectitintheRenderingspaneandclickRemoveRendering( ).Whenyouremoveallmemoryrenderingsforamonitoredexpression,variable,or
register,theRenderingspanewillbepopulatedwiththememoryrenderingselectionlist.Fromthislist,youcanselectthedataformatthatyouwanttouseforthememoryrendering
andthenclickAddRendering(s).
4.7.9.3.Workingwithmemorymonitors
ToviewthecontentsofmemoryfromtheMemoryview:
1. IntheMonitorspane,selectthememorymonitorthatcontainsthememorylocationthatyouwanttoview.MemorywillappearintheRenderingspane,whereyouwill
performallothersteps.Ifyouhaveaddedmultiplerenderings,selectthetabthatcontainstherenderingthatyouwanttoview.
2. Ifdesired,splittheRenderingspanebyselectingtheToggleSplitPanepushbutton( ).Bydefault,theMemoryviewonlydisplaysonerenderingpane.Whenyouclick
ToggleSplitPane,asecondrenderingopensanddisplaysasasplitpane.
3. Ifnecessary,usethescrollbarintherenderingtoviewmemorylocationsaboveorbelowthebaseaddressofthememorymonitorbeingshownbythecurrentrendering.
Alternatively,youcanrightclickintherenderingandchoosetheGotoAddresspopupmenuitemorhitCtrl+G.Thiswillopenasectionatthebottomoftherendering,in
whichyoucanperformthefollowingactions:
SelecttheGotoAddresspulldownmenuitemandthenenteranaddressthatyouwanttojumpto.Therenderingwillbepositionedsothattheaddressenteredis
visibleandselected.
SelecttheGotoOffsetpulldownmenuitemandthenentertheoffset.Therenderingwillbepositionedsothattheaddressoftheexpression(baseaddress),plusthe
offsetentered,isvisibleandselected.Anegativevaluewillpositiontherenderingbackfromthebaseaddress.
SelecttheJumpMemoryUnitspulldownmenuitem.Thisfunctiontakesthecurrentlyselectedaddressandaddsthenumberofmemoryunitsthatyouspecifytoit.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 120/322
12/10/2015 Javadevelopmentuserguide
Theresultingaddressisselected.Anegativevaluewillpositiontherenderingbackfromthecurrentaddress.
Foralloftheseentries,youcaninputthemasHEXbyselectingtheInputasHexcheckbox(ifthischeckboxisnotselected,inputwillbedecimal).Onceyouhavemade
theentryinthefield,hitEnterorclickOKtogotothelocationintherendering.Toclosethissection,clickCancelorhitCtrl+G.
Note:InputisalsotreatedasHEXifitisprefixedwith0x.
4. Ifyouwant,changethewidthofanycolumnbyclickingtheleftorrightsideofitsheadercellanddraggingittoalterthewidthofthecolumnorrightclickinsidetherendering
andselectResizetoFitfromthepopupmenusothatallcolumnsareresizedsothatalltextwithinthemcanbeviewed.Alternatively,youcanrightclickinsidetherendering
andselectFormatfromthepopupmenu.ThiswillopentheFormatdialogbox.Inthisdialogbox,youcansetthenumberofunitsperrowandthenumberofunitspercolumn.
Asyoumakethesesettings,aPreviewwindowinthedialogboxdisplaystherenderinglayoutthatyouaresetting.Tosavethesesettingsasthedefaultlayout,clickSaveas
Defaults.
5. YoucanalsohideelementsoftheMemoryviewforeasierviewing:
YoucanhidetheMonitorspanebydeselectingtheToggleMemoryMonitorsPanetoggle.
YoucanhidetheAddresscolumnbyrightclickinginsidetherenderingandselectingHideAddressColumn.Torestoreatheaddresscolumnwhenitishidden,right
clickinsidetherenderingandselectShowAddressColumnfromthepopupmenu.
Ifyouareinamemoryrenderingandmoveawayfromtheaddressthatyouoriginallysettomonitor,choosingtheResettoBaseAddresspopupmenuitemwillpositionthecursor
backtothebaseaddressofthememorymonitor.Alternatively,youcanresetallrenderingsforamemorymonitorbyrightclickingthemonitorandselectingReset(or,youcanselect
multiplemonitorsandchoosethisaction).Whenyouresetamonitor,bydefault,thevisiblerenderingswillberesettothebaseaddress.ToresetallrenderingsinthecurrentMemory
viewtothebaseaddress,modifytheMemoryviewpreferences.
4.7.9.4.Changingthecontentsofamemorylocation
TochangethecontentsofamemorylocationinamemorymonitorintheMemoryview:
1. IntheMonitorspane,selectthememorymonitorthatcontainsthememorylocationthatyouwanttoedit.MemorywillappearintheRenderingspane,whereyouwillperform
allothersteps.Ifyouhaveaddedmultiplerenderings,selectthetabthatcontainstherenderingthatyouwanttoedit.
2. Scrolldowntothememorylocationyouwanttochange.Alternatively,rightclickinthemonitorandchoosetheGotoAddresspopupmenuitem.ThiswillopenaGoTo
Addresssectionatthebottomoftherendering,inwhichyoucanenteranaddressthatyouwanttojumpto.
3. Selecttherowcontainingthevaluethatyouwanttochangeandthendoubleclickthevaluethatyouwanttochange.
Tip:Iftherenderingiscurrentlyinfocus,youdonotneedtodoubleclickthevaluethatyouwanttochangetobeabletoeditit.Rather,youcansimplystarttypingthechange
andtheeditorwillactivate.
4. Enteravalidvalueforthatmemorylocation.
5. PressEntertosubmitthechange.Thedebuggerchecksforavalidvalue.
4.7.9.5.Memoryviewpreferences
Youcansettablerendering,codepage,andpaddedstringpreferencesformemoryrenderings.Inaddition,youcanmodifythepreferredbehaviorforresettingmemoryrenderings.
MemoryviewpreferencedialogboxesareopenedfromtheMemoryviewdownarrowiconmenu.ToopentheMemoryviewPreferencesdialogbox,clicktheMemoryviewdown
arrowiconandselectPreferencesfromthemenu.ToopentheMemoryviewtablerenderingsPreferencesdialogbox,clicktheMemoryviewdownarrowiconandselectTable
RenderingsPreferencesfromthemenu.
Torestoreanychangesthatyoumakeinthepreferencestotheirdefaultsettings,clickRestoreDefaults.
Preferences:ResetMemoryMonitor
Youcanresetarenderingtothebaseaddressifyouhavemovedawayfromit.Whenyouresetarenderingtothebaseaddress,youcansetittoresetonlythevisiblerenderingsor
youcansetittoresetallrenderings.Ifyouchoosetoresetallrenderings,performanceoftheresetoperationcanbenegativelyimpacted.Tosetthispreference,openthe
PreferencesdialogboxandthenselecttheResetMemoryMonitornode.IntheResetMemoryMonitorpage,choosetheappropriateradiobutton.
Preferences:PaddedString
Thepaddedstringisthestringthatwillappearinmemorycontentswhenmemorycannotberetrieved.Tosetthepaddedstring,openthePreferencesdialogboxandselectthe
PaddedStringnode.InthePaddedStringpage,specifythestringthatyouwanttodisplaywhenmemorycontentscannotbedetermined.
Preferences:SelectCodepages
WhenmonitoringASCIIandEBCDICtextbasedrenderings(andmappedmemory,ifitisavailableintheproductthatyouinstalledthisdebuggerwith)intheRenderingspane,you
cansetthecodepageinwhichyouwanttherenderingtobedisplayed.
TosetthecodepageforrenderingmemorytoASCII/EBCDIC,openthePreferencesdialogboxandselecttheSelectCodepagesnode.IntheSelectCodepagespage,specifythe
codepageofthecharactersetthatyouwanttochange(forASCIIrenderings,EBCDICrenderings,orboth).
TableRenderingsPreferences
Tosetpreferencesformemoryrenderingsthataredisplayedinatable,clicktheMemoryviewdownarrowiconandselectTableRenderingsPreferences.Intheresulting
preferencesdialogbox,therearetwooptions:
Automaticradiobutton:SelectthisifyouwantthedebuggertoautomaticallypreloadabufferofmemorybeforeandafterthevisibleregionintheMemoryview.Whenyou
selectthissetting,youcaneasilyscrollawayfromthevisibleregionofmemorywithscrollandpageup/downactions.
Ifthebuffersizeislarge,theperformanceofrefreshingtheMemoryviewcanbenegativelyimpacted(theMemoryviewrefresheswhenthereisapotentialformemorychange
so,forexample,theMemoryviewrefresheswhenyoustep,suspendafterrunning,changeavariableorregister,ormodifymemory).Thisisbecausearequestformore
memorymustbemadefromthedebugengineforeachrefresh.Ontheotherhand,ifthebuffersizeistoosmall,theperformanceofscrollingcanbenegativelyimpacted.This
isbecausearequestformorememorymustbemadefromthedebugenginewhenthebufferisexhausted.Giventhisperformancetradeoff,youneedtosetthisoptiontosuit
yourneeds.
Manualradiobutton:Ifyouselectthissetting,thenthenumberoflinesperpagethatyouspecifywillbeloadedintotheRenderingspane.Whenusingthissetting,youhave
morecontrolinchoosingexactlywhatyouwanttomonitor,however,youwillnotbeabletoscrolloutsidethebufferdefinedbythispagesizesetting.Instead,toviewmemory
fromthenextpageorpreviouspage,youmustrightclicktousethePreviousPageandNextPageactionsfromthepopupmenu.
Ifthebuffersizeislarge,theperformanceofrefreshingtheMemoryviewcanbenegativelyimpacted(theMemoryviewrefresheswhenthereisapotentialformemorychange
so,forexample,theMemoryviewrefresheswhenyoustep,suspendafterrunning,changeavariableorregister,ormodifymemory).Thisisbecausearequestformore
memorymustbemadefromthedebugengineforeachrefresh.
4.7.9.6.WorkingwithmultipleMemoryviews
YoucanaddadditionalMemoryviewstotheworkbench.Todothis,clickNewMemoryView( ).WhenyouhavemultipleMemoryviewsopen,youcannotlinktheirrenderingsto
eachother.However,youcanpinthecontentsofaMemoryviewsothatmemoryrenderingsthatareaddedtooneviewdonotaffecttheotherview.Topinamemorymonitor,
ensurethatthePinMemoryMonitorbutton( )intheMemoryviewistoggledon.IfyouthengotoanotherMemoryviewandaddamemorymonitor,itwillshowupinboth
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 121/322
12/10/2015 Javadevelopmentuserguide
Memoryviews,however,thememoryrenderingthatiscurrentlydisplayedinthepinnedmonitorwillnotchange.
WhenyouaddanewMemoryview,itsRenderingspanewillbepopulatedwiththememoryrenderingselectionlist.Fromthislist,youcanselectthedataformatthatyouwantto
useforthememoryrenderingandthenclickAddRendering(s).
4.7.9.7.RemovingmemorymonitorsfromtheMemoryview
ToremoveamemorymonitorfromtheMemoryview:
1. Selectthememorymonitorthatyouwanttoremove(byselectingitinthelistintheMonitorspane).
2. ClicktheRemoveMemoryMonitorpushbutton( ).
Toremovemultiplememorymonitors,selectthemusingthekeyboardCtrlorShiftkeys,andthenclickRemoveMemoryMonitor.Toremoveallmemorymonitors,clickRemove
All.
Note:Ifyouhaveaddedmultiplerenderingsforamemorymonitor,allrenderingswillberemovedwhenyouchoosetoremovethemonitor.
4.8.1.CreatingaJavaScrapbookPage
ThescrapbookallowsJavaexpressions,toberun,inspected,anddisplayedunderthecontrolofthedebugger.Breakpointsandexceptionsbehaveastheydoinaregulardebug
session.
Codeiseditedonascrapbookpage.AVMislaunchedforeachscrapbookpageinwhichexpressionsarebeingevaluated.Thefirsttimeanexpressionisevaluatedinascrapbook
pageafteritisopened,aVMislaunched.TheVMforapagewillremainactiveuntilthepageisclosed,terminatedexplicitly(inthedebuggerorviatheStoptheEvaluationbuttonin
theeditortoolbar),orwhenaSystem.exit()isevaluated.
Thereareseveralwaystoopenthe NewJavaScrapbookPagewizard.
Createafilewitha.jpageextension
Fromthemenubar,selectFile>New>Other....ThenselectJava>JavaRun/Debug>ScrapbookPage.ThenclickNext.
Onceyou'veopenedtheNewJavaScrapbookPagewizard:.
1. IntheEnterorselectthefolderfield,typeorclickBrowsetoselectthecontainerforthenewpage.
2. IntheFilenamefield,typeanameforthenewpage.The.jpageextensionwillbeaddedautomaticallyifyoudonottypeityourself.
3. ClickFinishwhenyouaredone.Thenewscrapbookpageopensinaneditor.
Scrapbook
Javaprojects
Runninganddebugging
Javascrapbookpage
4.8.2.Inspectingtheresultofevaluatinganexpression
InspectingshowstheresultofevaluatinganexpressionintheExpressionsview.
1. Inthescrapbookpage,eithertypeanexpressionorhighlightanexistingexpressiontobeinspected.Forexample:System.getProperties()
2. ClicktheInspectbuttoninthetoolbar(orselectInspectfromtheselection'spopupmenu).
3. Theresultoftheinspectionappearsinapopup.
4. Theresultcanbeinspectedlikeavariableinthedebugger(forexample,childrenoftheresultcanbeexpanded).
Scrapbook
CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Executinganexpression
Viewingruntimeexceptions
Expressionsview
Javascrapbookpage
4.8.3.Displayingtheresultofevaluatinganexpression
Displayingshowstheresultofevaluatinganexpressioninthescrapbookeditor.
1. Inthescrapbookpage,eithertypeanexpressionorhighlightanexistingexpressiontobedisplayed.Forexample:System.getProperties()
2. ClicktheDisplaybuttoninthetoolbar(orselectDisplayfromtheselection'spopupmenu.)
3. Theresultoftheevaluationappearshighlightedinthescrapbookeditor.Theresultdisplayediseither
thevalueobtainedbysendingtoString()totheresultoftheevaluation,or
whenevaluatingaprimitivedatatype(e.g.,anint),theresultisthesimplevalueoftheresult.
Forexample:
Typeandhighlightnewjava.util.Date()intheeditor,andclickDisplay.Aresultsuchas(java.util.Date)TueJun1214:03:17CDT2001appearsintheeditor.
Asanotherexample,typeandhighlight3+4intheeditor,andpressDisplay.Theresult(int)7isdisplayedintheeditor.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 122/322
12/10/2015 Javadevelopmentuserguide
Scrapbook
Executinganexpression
Inspectingtheresultofevaluatinganexpression
Viewingruntimeexceptions
Javascrapbookpage
4.8.4.Executinganexpression
Executinganexpressionevaluatesanexpressionbutdoesnotdisplayaresult.
IfyouselecttheexpressiontoexecuteandclicktheExecutebuttoninthetoolbar,noresultisdisplayed,butthecodeisexecuted.
Forexample,ifyoutypeandhighlightSystem.out.println("HelloWorld"),andclicktheExecutebutton,HelloWorldappearsintheConsoleview,butnoresultisdisplayedin
thescrapbookeditorortheExpressionsview.
Javaviews
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Viewingruntimeexceptions
Expressionsview
Consoleview
4.8.5.Usingcodeassist
ThescrapbookeditorsupportscodeassistsimilarlytotheregularJavaeditor.
Forexample,typeTestCaseinthescrapbookeditorandpressCtrl+Space.Codeassistpromptsyouwithpossiblecompletions.
4.8.6.Scrapbookerrorreporting
Javascrapbookerrorsarereportedinthescrapbookpageeditor.
Viewingcompilationerrors
Viewingruntimeexceptions
4.8.6.1.Viewingcompilationerrors
Ifyoutrytoevaluateanexpressioncontainingacompilationerror,itwillbereportedinthescrapbookeditor.
Forexample,typeandselectthe(invalid)expressionSystem.println("hi")intheeditorandclickExecuteinthetoolbar.
TheerrormessageThemethodprintln(java.lang.String)isundefinedforthetypejava.lang.Systemappearsintheeditoratthepointoftheerror.
4.8.6.2.Viewingruntimeexceptions
Ifanexpressionyouevaluatecausesaruntimeexception,theexceptionwillbereportedintheeditor.Forexample:
TypeandselecttheexpressionObjectx=nullx.toString()intheeditorandclickDisplayinthetoolbar.
Theerrormessage:
Anexceptionoccurredduringevaluation:java.lang.NullPointerException
willbedisplayedintheeditor.
Javaeditor
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Executinganexpression
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 123/322
12/10/2015 Javadevelopmentuserguide
4.9.1.Usingthebatchcompiler
Findingthebatchcompiler
ThebatchcompilerclassislocatedintheJDTCoreplugin.Thenameoftheclassisorg.eclipse.jdt.compiler.batch.BatchCompiler.Itispackagedinto
plugins/org.eclipse.jdt.core_<version>.jar.Since3.2,itisalsoavailableasaseparatedownload.Thenameofthefileisecj.jar.Itscorrespondingsourceisalsoavailable.
Togetthem,gotothedownloadpageandsearchforthesectionJDTCoreBatchCompiler.Thisjarcontainsthebatchcompilerandthejavacantadapter.
Since3.3,thisjaralsocontainsthesupportforjsr199(CompilerAPI)andthesupportforjsr269(Annotationprocessing).Inordertousetheannotationsprocessingsupport,a1.6
VMisrequired.
SoitcanbeusedasastandaloneapplicationandinsideanAntbuildoutsideofEclipse.
Runningthebatchcompiler
Fromthecommandline.
javajarorg.eclipse.jdt.core_<version>.jarclasspathrt.jarA.java
or:
javajarecj.jarclasspathrt.jarA.java
Usingthestaticcompile(StringcommandLine,PrintWriteroutWriter,PrintWritererrWriter,CompilationProgressprogress)methodoftheclass
BatchCompiler.
org.eclipse.jdt.core.compiler.CompilationProgressprogress=null//instantiateyoursubclass
org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
"classpathrt.jarA.java",
newPrintWriter(System.out),
newPrintWriter(System.err),
progress)
Youcancontrolhowprogressisreported,orhowthebatchcompileriscanceled,bysubclassingtheclassorg.eclipse.jdt.compiler.CompilationProgress.
Whichoptionsareavailable?
Therecommendedoptionshaveanorangebackground.
Whensomeoptionsarebeingsetmultipletimes,thebatchcompilerconsumesthemfromlefttoright.Whenthewarningoption(warn:....)isusedwithout'+'or'',thisoverridesthe
setofwarningspreviouslyspecified.Soyoushouldmakesurethatsuchanoptionisgivenbeforeanyotherusageofthewarnoption.
Sameappliesfortheerr:option.
Name Usage
Classpathoptions
bootclasspath<dir1><dir2>...<dirP> Thisisalistofdirectoriesorjarfilesusedtobootstraptheclassfilesusedbythecompiler.BydefaultthelibrariesoftherunningVM
areused.Entriesareseparatedbytheplatformpathseparator.
Eachdirectoryorfilecanspecifyaccessrulesfortypesbetween'['and']'.
Ifnobootclasspathisspecified,thecompilerwillinferitusingthefollowingsystempropertiessun.boot.class.path,
vm.boot.class.pathororg.apache.harmony.boot.class.pathinthisorderrespectively.
cp Thisisalistofdirectoriesorjarfilesusedtocompilethesourcefiles.Thedefaultvalueisthevalueoftheproperty"java.class.path".
classpath<dir1><dir2>...<dirP> Entriesareseparatedbytheplatformpathseparator.
Eachdirectoryorfilecanspecifyaccessrulesfortypesbetween'['and']'(e.g.[X]toforbidaccesstotypeX,[~X]todiscourage
accesstotypeX,[+p/X:p/*]toforbidaccesstoalltypesinpackagepbutallowaccesstop/X).
ThecompilerfollowstheClassPathclausesofjarfiles'manifestsrecursivelyandappendseachreferencedjarfiletotheendofthe
classpath,provideditisnotontheclasspathyet.
extdirs<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythelocationofextensionzip/jarfiles.Entriesareseparatedbytheplatformpathseparator.
endorseddirs<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythelocationofendorsedzip/jarfiles.Entriesareseparatedbytheplatformpathseparator.
sourcepath<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythesourcefiles.Entriesareseparatedbytheplatformpathseparator.
Eachdirectorycanspecifyaccessrulesfortypesbetween'['and']'.
d<dir1>|none Thisisusedtospecifyinwhichdirectorythegenerated.classfilesshouldbedumped.Ifitisomitted,nopackagedirectorystructure
iscreated.
Ifyouwanttogenerateno.classfileatall,usednone.
encoding<encodingname> Specifydefaultencodingforallsourcefiles.Customencodingcanalsobespecifiedonaperfilebasisbysuffixingeachinputsource
file/foldernamewith[<encodingname>].ForexampleX.java[UTF8]wouldspecifytheUTF8encodingforthecompilationunitX.java
locatedinthecurrentuserdirectory.
Ifmultipledefaultsourcefileencodingsarespecified,thelastonewillbeused.
Forexample:
...encodingUTF8X.java[Cp1252]Y.java[UTF16]Z.java....
MostsourcefileswillbereadusingUTF8encoding(thisincludesZ.java).X.javawillbereadusingCp1252encodingand
Y.javawillbereadusingUTF16encoding.
...encodingUTF8encodingUTF16....
AllsourcefileswillbereadusingUTF16encoding.TheencodingoptionforUTF8isignored.
...encodingCp1252/foo/bar/X.java[UTF16]/foo/bar[UTF8]....
AllsourcefileswillbereadusingCp1252encoding.X.javaistheonlyfileinsidethe/foo/bardirectorytobereadusingthe
encodingUTF16.AllotherfilesinthatdirectorywilluseUTF8encoding.
Complianceoptions
target1.1to1.8(or8,8.0,etc.) Thisspecifiesthe.classfiletargetsetting.Thepossiblevalueare:
1.1(majorversion:45minor:3)
1.2(majorversion:46minor:0)
1.3(majorversion:47minor:0)
1.4(majorversion:48minor:0)
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 124/322
12/10/2015 Javadevelopmentuserguide
1.5,5or5.0(majorversion:49minor:0)
1.6,6or6.0(majorversion:50minor:0)
1.7,7or7.0(majorversion:51minor:0)
1.8,8or8.0(majorversion:52minor:0)
Defaultsare:
1.1in1.3mode
1.2in1.4mode
1.5in1.5mode
1.6in1.6mode
1.7in1.7mode
1.8in1.8mode
clcd1.1canbeusedtogeneratetheStackMapattribute.
1.3 Setcompliancelevelto1.3.Implicitsource1.3target1.1.
1.4 Setcompliancelevelto1.4(default).Implicitsource1.3target1.2.
1.5 Setcompliancelevelto1.5.Implicitsource1.5target1.5.
1.6 Setcompliancelevelto1.6.Implicitsource1.6target1.6.
1.7 Setcompliancelevelto1.7.Implicitsource1.7target1.7.
1.8 Setcompliancelevelto1.8.Implicitsource1.8target1.8.
source1.1to1.8(or8,8.0,etc.) Thisisusedtospecifythesourcelevelexpectedbythecompiler.
Thepossiblevalueare:
1.3
1.4
1.5,5or5.0
1.6,6or6.0
1.7,7or7.0
1.8,8or8.0
Defaultsare:
1.3in1.3mode
1.3in1.4mode
1.5in1.5mode
1.6in1.6mode
1.7in1.7mode
1.8in1.8mode
In1.4,assertistreatedasakeyword.In1.5and1.6,enumandassertaretreatedaskeywords.
Warningoptions
?:warnhelp:warn Displayadvancedwarningoptions
warn:... Specifythesetofenabledwarnings.
warn:none disableallwarnings
warn:<warningtokensseparatedby,> enableexactlythelistedwarnings
warn:+<warningtokensseparatedby,> enableadditionalwarnings
warn:<warningtokensseparatedby,> disablespecificwarnings
Examples:
warn:unusedLocal,deprecationenablesonlythegiventwowarningoptionsanddisablesalltheotheroptions
warn:unusedLocal,deprecation,+fallthroughdisablesunusedLocalanddeprecation,enablesfallthrough,andleavestheother
warningoptionsuntouched
InthecolumnDefaultbelow,amark"+/"indicatesthatanoptioncoversseveralfinegrainedwarningvariants,someofwhichare
enabledbydefault,othersdisabled.Thismeansthatspecifyingthegivenoptionwith"+"willenablemorewarningsthanthedefault,
andspecifying""disablessomethatareenabledbydefault.
Default Tokenname Description
+/ allDeadCode deadcodeincludingtrivialif(DEBUG)check
+/ allDeprecation deprecationeveninsidedeprecatedcode
allJavadoc invalidormissingJavadoc
allOverann allmissing@Overrideannotations(superclassandsuperinterfaces)
allstaticmethod allmethodcanbedeclaredasstaticwarnings
+ assertIdentifier occurrenceofassertusedasidentifier
boxing autoboxingconversion
+ charConcat whenachararrayisusedinastringconcatenationwithoutbeing
convertedexplicitlytoastring
+ compareIdentical comparingidenticalexpressions
conditionAssign possibleaccidentalbooleanassignment
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 125/322
12/10/2015 Javadevelopmentuserguide
+ constructorName methodwithconstructorname
+ deadCode deadcodeexcludingtrivialif(DEBUG)check
depann missing@Deprecatedannotation
+/ deprecation usageofdeprecatedtypeormemberoutsidedeprecatedcode
+ discouraged useoftypesmatchingadiscouragedaccessrule
emptyBlock undocumentedemptyblock
+ enumIdentifier occurrenceofenumusedasidentifier
+ enumSwitch incompleteenumswitch
enumSwitchPedantic reportmissingenumswitchcaseseveninthepresenceofadefaultcase
fallthrough possiblefallthroughcase
fieldHiding fieldhidinganothervariable
+ finalBound typeparameterwithfinalbound
+ finally finallyblocknotcompletingnormally
+ forbidden useoftypesmatchingaforbiddenaccessrule
hashCode missinghashCode()methodwhenoverridingequals()
+/ hiding macroforfieldHiding,localHiding,maskedCatchBlock,andtypeHiding
includeAssertNull raisenullwarningsforvariablesthatgottaintedinanassertexpression
indirectStatic indirectreferencetostaticmember
inheritNullAnnot considernullannotationsasbeinginheritedfromanoverriddenmethodto
anyoverridingmethods
+ intfAnnotation annotationtypeusedassuperinterface
+ intfNonInherited interfacenoninheritedmethodcompatibility
intfRedundant findredundantsuperinterfaces
invalidJavadoc macrototogglethe'malformedJavadoccomments'optionandallitssub
optionslistedbelow
invalidJavadocTag reportinvalidJavadoctagsinJavadoccomments.
invalidJavadocTagDep reportinvaliddeprecatedreferencesinJavadoctagarguments
invalidJavadocTagNotVisible reportinvalidnonvisiblereferencesinJavadoctagarguments
invalidJavadocVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formalformed
Javadoctagwarnings.Usageexample:invalidJavadocVisibility(public)
javadoc invalidJavadoc
localHiding localvariablehidinganothervariable
+ maskedCatchBlock hiddencatchblock
missingJavadocTags macrototogglethe'missingJavadoctags'optionandallitssuboptions
listedbelow
missingJavadocTagsMethod reportmissingJavadoctagsforamethod'stypeparameters
missingJavadocTagsOverriding reportmissingJavadoctagsinoverridingmethods
missingJavadocTagsVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formissing
Javadoctagswarnings.Usageexample:
missingJavadocTagsVisibility(public)
missingJavadocComments macrototogglethe'missingJavadoccomments'optionandallitssub
optionslistedbelow
missingJavadocCommentsOverriding reportmissingJavadoccommentsinoverridingmethods
missingJavadocCommentsVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formissing
Javadoccommentswarnings.Usageexample:
missingJavadocCommentsVisibility(public)
nls nonnlsstringliterals(lackingoftags//$NONNLS<n>)
+ noEffectAssign assignmentwithnoeffect
+ nonnullNotRepeated nonnullparameterannotationfromoverriddenmethodisnotrepeatedinan
overridingmethod.IseffectiveonlywiththenullAnnotoptionenabled.
+/ null potentialmissingorredundantnullcheck
nullAnnot enableannotationbasednullanalysis.
Ifdesired,theannotationtypestobeinterpretedbythecompilercanbe
specifiedbyappending(nullable|nonnull|nonnullbydefault),whereeach
annotationtypeisspecifiedusingitsfullyqualifiedname.
Usageexample:nullAnnot(p.Nullable|p.NonNull|p.NonNullByDefault)
Enablingthisoptionenablesallnullannotationrelatedsuboptions.These
canbeindividuallycontrolledusingoptionslistedbelow
nullAnnotConflict reportconflictsbetweennullannotationspecifiedandnullnessinferred.Is
effectiveonlywiththenullAnnotoptionenabled.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 126/322
12/10/2015 Javadevelopmentuserguide
nullAnnotRedundant reportredundantspecificationofnullannotation.Iseffectiveonlywiththe
nullAnnotoptionenabled.
nullDereference missingnullcheck
nullUncheckedConversion [email protected]
effectiveonlywiththenullAnnotoptionenabled.
overann missing@Overrideannotation(superclassonly)
paramAssign assignmenttoaparameter
+ pkgDefaultMethod attempttooverridepackagedefaultmethod
+ raw usageaofrawtype(insteadofaparameterizedtype)
+/ resource (potentially)unsafeusageofresourceoftypeCloseable
semicolon unnecessarysemicolonoremptystatement
+ serial missingserialVersionUID
specialParamHiding constructororsetterparameterhidinganotherfield
+/ staticaccess macroforindirectStaticandstaticReceiver
staticmethod aninstancemethodthatcouldbeasastaticmethod
+ staticReceiver ifanonstaticreceiverisusedtogetastaticfieldorcallastaticmethod
super overridingamethodwithoutmakingasuperinvocation
+ suppress enable@SuppressWarnings
switchDefault switchstatementlackingadefaultcase
syncOverride missingsynchronizedinsynchronizedmethodoverride
syntacticAnalysis performsyntaxbasednullanalysisforfields
syntheticAccess whenperformingsyntheticaccessforinnerclass
tasks enablesupportfortaskstagsinsourcecode
+ typeHiding typeparameterhidinganothertype
+ unavoidableGenericProblems reportevenunavoidabletypesafetyproblemsduetorawAPIs
+ unchecked uncheckedtypeoperation
unnecessaryElse unnecessaryelseclause
unqualifiedField unqualifiedreferencetofield
+/ unused macroforunusedImport,unusedLabel,unusedLocal,unusedPrivate,
unusedThrown,unusedTypeArgs,andunusedTypeParameter
unusedAllocation allocatinganobjectthatisnotused
unusedArgument unusedmethodparameter(deprecatedoptionuseunusedParaminstead)
+ unusedImport unusedimportreference
+ unusedLabel unusedlabel
+ unusedLocal unusedlocalvariable
+ unusedParam unusedmethodparameter
+ unusedParamImplementing unusedparameterforimplementingmethod
+ unusedParamIncludeDoc unusedparameterdocumentedinaJavadoccommenttag
+ unusedParamOverriding unusedparameterforoverridingmethod
+ unusedPrivate unusedprivatememberdeclaration
unusedThrown unuseddeclaredthrownexception
unusedThrownIncludeDocComment unuseddeclaredthrownexceptiondocumentedinaJavadoccomment
tag
unusedThrownExemptExceptionThrowable reportunuseddeclaredthrownexceptionbutexemptExceptionand
Throwable
unusedThrownWhenOverriding unuseddeclaredthrownexceptioninoverridingmethod
+ unusedTypeArgs unusedtypeargumentsformethodandconstructor
+ unusedTypeParameter unusedtypeparameter
uselessTypeCheck unnecessarycast/instanceofoperation
+ varargsCast varargsargumentneedexplicitcast
+/ warningToken unhandledorunusedwarningtokenin@SuppressWarnings
nowarn Nowarning(equivalenttowarn:none)
err:... Specifythesetofenabledwarningsthatareconvertedtoerrors.
e.g.err:unusedLocal,deprecation
unusedLocalanddeprecationwarningswillbeconvertedtoerrors.Allotherwarningsarestillreportedaswarnings.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 127/322
12/10/2015 Javadevelopmentuserguide
err:<warningtokensseparatedby,> convertexactlythelistedwarningstoerrors
err:+<warningtokensseparatedby,> convertadditionalwarningstoerrors
err:<warningtokensseparatedby,> removespecificwarningsfrombeingconvertedtoerrors
deprecation Equivalenttowarn:+deprecation.
properties<file> Setwarnings/errorsoptionbasedonthepropertiesfilecontents.Thisoptioncanbeusedwithnowarn,err:..orwarn:..options,but
thelastoneonthecommandlinesetstheoptionstobeused.
Thepropertiesfilecontentscanbegeneratedbysettingprojectspecificsettingsonanexistingjavaprojectandusingthefilein
.settings/org.eclipse.jdt.core.prefsfileasapropertiesfile,orasimpletextfilethatisdefinedentry/valuepairsusingthe
constantsdefinedintheorg.eclipse.jdt.core.JavaCoreclass.Ofthoseconstantsdeclaredinthisclass,alloptionsstartingwith
"org.eclipse.jdt.core.compiler."areinterpretedbythebatchcompiler.
...
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
...
ToensurethatapropertyfilehasthesameeffectwhenusedintheIDEandforthebatchcompiler,useofthepropertiesoption
willchangethedefaultsforafewoptions:
g defaultchangedtoallenabled
preserveAllLocals defaultchangedtoenabled
enableJavadoc defaultchangedtoenabled
error/warningforbidden defaultchangedtoerror
Debugoptions
g[:none|:lines,vars,source] Setthedebugattributeslevel
g Alldebuginfo(equivalenttog:lines,vars,source)
g:none Nodebuginfo
g:[lines,vars,source] Selectivedebuginfo
Notspecifyingthisoptionisequivalenttosettingg:lines,source.
preserveAllLocals Explicitlyrequestthecompilertopreservealllocalvariables(fordebugpurpose).Ifomitted,thecompilerwillremoveunusedlocals.
parameters Explicitlyrequestthecompilertopreserveinformationabouttheformalparametersofamethod(suchastheirnames)tobeaccessed
fromreflectionlibraries,annotationprocessing,codeweaving,andinthedebugger.Thisoptionissupportedfromtargetlevel1.8and
later.
Annotationprocessingoptions(requirea1.6VMoraboveandareusedonlyifthecomplianceis1.6)
Akey[=value] Annotationprocessorsoptionsthatarepassedtoannotationprocessors.keyismadeofidentifiersseparatedbydots
proc:[only|none] Ifproc:onlyisspecified,theannotationprocessorswillrunbutnocompilationwillbeperformed.Ifproc:noneisspecified,
annotationprocessorswillnotbediscoveredorruncompilationwillproceedasifnoannotationprocessorswerefound.Bydefaultthe
compilermustsearchtheclasspathforannotationprocessors,sospecifyingproc:nonemayspeedcompilationifannotation
processingisnotrequired.
processor<class1[,class2,...]> Qualifiedclassnamesofannotationprocessorstorun.Ifspecified,thenormalprocessordiscoveryprocesswillbeskipped.
processorpath<dir1><dir2>...<dirP> Alistofdirectoriesorjarfileswhichwillbesearchedforannotationprocessors.Entriesareseparatedbytheplatformpathseparator.
Ifnotspecified,theclasspathwillbesearchedinstead.
s<dir> Thedirectorywheregeneratedsourcefileswillbecreated.
XprintProcessorInfo Printinformationaboutwhichannotationsandwhichelementsaprocessorisaskedtoprocess
XprintRounds Printinformationaboutannotationprocessingrounds
classNames<class1[,class2,...]> Qualifiednamesofbinarytypesthatneedtobeprocessed
Ignoredoptions(forcompatibilitywithjavacoptions)
J<option> Passoptiontothevirtualmachine
X<option> Specifynonstandardoption.Xemacsisnotignored.
X Printnonstandardoptionsandexit
O Optimizeforexecutiontime
Advancedoptions
@<file> Readcommandlineargumentsfromfile
maxProblems<n> Maxnumberofproblemspercompilationunit(100bydefault)
log<filename> Specifyalogfileinwhichalloutputfromthecompilerwillbedumped.Thisisreallyusefulifyouwanttodebugthebatchcompileror
getafilewhichcontainsallerrorsandwarningsfromabatchbuild.Iftheextensionis.xml,thegeneratedlogwillbeanxmlfile.
genericsignature Explicitlyrequestthecompilertopreserveinformationaboutgenericsignatureoflambdaexpressions.
Xemacs Useemacsstyletopresenterrorsandwarningslocationsintotheconsoleandregulartextlogs.XMLlogsareunaffectedbythis
option.Withthisoptionactive,themessage:
2.WARNINGin/workspace/X.java
(atline8)...
ispresentedas:
/workspace/X.java:8:warning:Themethod...
proceedOnError[:Fatal] Keepcompilinginspiteoferrors,dumpingclassfileswithproblemmethodsorproblemtypes.Thisisrecommendedonlyifyouwant
tobeabletorunyourapplicationevenifyouhaveremainingerrors.
With":Fatal",alloptionalerrorsaretreatedasfatalandthisleadstocodethatwillabortifanerrorisreachedatruntime.Without
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 128/322
12/10/2015 Javadevelopmentuserguide
":Fatal",optionalerrorsdon'tpreventthepropercodegenerationandtheproduced.classfilescanberunwithoutaproblem.
verbose Printaccessed/processedcompilationunitsintheconsoleorthelogfileifspecified.
referenceInfo Computereferenceinfo.Thisisusefulonlyifconnectedtothebuilder.Thereferenceinfosareuselessotherwise.
progress Showprogress(onlyinlogmode).
time Displayspeedinformation.
noExit DonotcallSystem.exit(n)atendofcompilation(n=0ifnoerror).
repeat<n> Repeatcompilationprocess<n>times(perfanalysis).
inlineJSR InlineJSRbytecode(implicitiftarget>=1.5).
enableJavadoc ConsiderreferencesinsideJavadoc.TheJavadocoptionsareeffectiveonlywhenthisoptionisenabled.
missingNullDefault Whenannotationbasednullanalysisisenabled(using"nullAnnot",above),thisoptionwillraiseawarningwheneverthereisno
defaultannotationonapackageoratype.
annotationpath Whenannotationbasednullanalysisisenabled(using"nullAnnot",above),thisoptiondefineslocationswheretofindexternal
annotationstosupportannotationbasednullanalysis.
Thevalueofthisoptionsisalistofdirectoriesorzipfiles.Entriesareseparatedbytheplatformpathseparator.
ThespecialnameCLASSPATHwillcauselookupofexternalannotationsfromtheclasspathandsourcepath.
Helpingoptions
?help Displaythehelpmessage.
vversion Displaythebuildnumberofthecompiler.Thisisveryusefultoreportabug.
showversion Displaythebuildnumberofthecompilerandcontinue.Thisisveryusefultoreportabug.
Examples
d:\tempclasspath Itcompilesallsourcefilesind:\tempanditssubfolders.Theclasspathissimplyrt.jar.Itgeneratesalldebugattributesandallgenerated.classfiles
rt.jartimegd aredumpedind:\tmp.Thespeedofthecompilerwillbedisplayedoncethebatchprocessiscompleted.
d:/tmp
d:\temp\Test.java ItcompilesonlyTest.javaanditsdependantfilesifany,retrievingdependantfilesfromd:\temp.Theclasspathisd:\tempfollowedbyrt.jar,which
classpath meansthatallnecessaryclassesaresearchedfirstind:\tempandtheninrt.jar.Itgeneratesnodebugattributesandallgenerated.classfilesare
d:\temprt.jarg:none dumpedind:\temp.
4.9.2.Usingtheantjavacadapter
TheEclipsecompilercanbeusedinsideanAntbuildfileusingthejavacadapter.InordertousetheEclipsecompiler,yousimplyneedtodefinethebuild.compilerpropertyinyour
buildfile.
Inordertogetthebatchcompilerworkinginanantbuildfile,theantruntimeclasspathneedstocontaintheEclipsebatchcompiler.Whenyourunyourantbuildfile:
1. outsideofEclipse:theeasiestwaytosetuptheantruntimeclasspathistoaddtheecj.jarfileusingthelibargumentordumpingitinsidetheANT_HOMElocation.
2. insideEclipseusingthesameJREthanEclipse:theEclipsebatchcompilerisimplicitlyaddedtotheantruntimeclasspath.
3. insideEclipseusingthedifferentJRE:theEclipsebatchcompilermustbeexplicitlyaddedtotheantruntimeclasspath.Thiscanbedoneusingtheecj.jarfileorusingthe
org.eclipse.jdt.corejarfileandthejdtCompilerAdapter.jarfilelocatedinsidetheorg.eclipse.jdt.corejarfile(thisjarfileneedstobeextractedfirst).
Hereisasmallexample:
<?xmlversion="1.0"encoding="UTF8"?>
<projectname="compile"default="main"basedir="../.">
<propertyname="build.compiler"value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<propertyname="root"value="${basedir}/src"/>
<propertyname="destdir"value="d:/temp/bin"/>
<targetname="main">
<javacsrcdir="${root}"destdir="${destdir}"debug="on"nowarn="on"extdirs="d:/extdirs"source="1.4">
<classpath>
<pathelementlocation="${basedir}/../org.eclipse.jdt.core/bin"/>
</classpath>
</javac>
</target>
</project>
ThesyntaxusedforthejavacAnttaskcanbefoundintheAntjavactaskdocumentation.ThecurrentadaptersupportstheJavacAnttask1.4.1upto1.6.5versions.
Ifyouareusingaversionabove1.5.0,youcanusethenestedcompilerargumentelement(<compilerarg>)tospecifycompilerspecificoptions.
...
<javacsrcdir="${root}"destdir="${destdir}"debug="on"nowarn="on"extdirs="d:/extdirs"source="1.4">
<classpath>
<pathelementlocation="${basedir}/../org.eclipse.jdt.core/bin"/>
</classpath>
<compilerargcompiler="org.eclipse.jdt.core.JDTCompilerAdapter"line="1.5warn:+boxing"/>
</javac>
...
Note:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 129/322
12/10/2015 Javadevelopmentuserguide
1. Topreventcompilerdependantbuildfiles,westronglyadviseyoutousea<compilerarg>whose"compiler"attributevalueisorg.eclipse.jdt.core.JDTCompilerAdapter.
Ifthisisnotset,thebuildfilecanonlybeusedwiththeEclipsecompiler.Ifset,thenestedcompilerargumentisignoredifthenameisdifferentfromthecompilername
specifiedbythebuild.compilerproperty.
2. <compilerarg>shouldnotbeusedtosetvaluesliketargetvalue,sourcevalue,debugoptions,oranyoptionsthatcouldbesetusingthedefinedattributesofthejavacant
task.Itsusagemustbereservedtopasscompilerspecificoptionslikewarningoptions.Whenacommandlineargumentisspecifiedmorethanonce,theEclipsebatch
compilercanreporterrorslike:
duplicatetargetcompliancesettingspecification:1.5
4.9.3.Excludingwarningsusing@SuppressWarnings
SinceJava5.0,youcandisablecompilationwarningsrelativetoasubsetofacompilationunitusingthejava.lang.SuppressWarningannotation.
@SuppressWarning("unused")publicvoidfoo(){
Strings
}
Withouttheannotation,thecompilerwouldcomplainthatthelocalvariablesisneverused.Withtheannotation,thecompilersilentlyignoresthiswarninglocallytothefoomethod.
Thisenablestokeepthewarningsinotherlocationsofthesamecompilationunitorthesameproject.
ThelistoftokensthatcanbeusedinsideaSuppressWarningsannotationis:
alltosuppressallwarnings
boxingtosuppresswarningsrelativetoboxing/unboxingoperations
casttosuppresswarningsrelativetocastoperations
depanntosuppresswarningsrelativetodeprecatedannotation
deprecationtosuppresswarningsrelativetodeprecation
fallthroughtosuppresswarningsrelativetomissingbreaksinswitchstatements
finallytosuppresswarningsrelativetofinallyblockthatdon'treturn
hidingtosuppresswarningsrelativetolocalsthathidevariable
incompleteswitchtosuppresswarningsrelativetomissingentriesinaswitchstatement(enumcase)
javadoctosuppresswarningsrelativetojavadocwarnings
nlstosuppresswarningsrelativetononnlsstringliterals
nulltosuppresswarningsrelativetonullanalysis
rawtypestosuppresswarningsrelativetousageofrawtypes
resourcetosuppresswarningsrelativetousageofresourcesoftypeCloseable
restrictiontosuppresswarningsrelativetousageofdiscouragedorforbiddenreferences
serialtosuppresswarningsrelativetomissingserialVersionUIDfieldforaserializableclass
staticaccesstosuppresswarningsrelativetoincorrectstaticaccess
staticmethodtosuppresswarningsrelativetomethodsthatcouldbedeclaredasstatic
supertosuppresswarningsrelativetooverridingamethodwithoutsuperinvocations
syntheticaccesstosuppresswarningsrelativetounoptimizedaccessfrominnerclasses
syncoverridetosuppresswarningsbecauseofmissingsynchronizewhenoverridingasynchronizedmethod
uncheckedtosuppresswarningsrelativetouncheckedoperations
unqualifiedfieldaccesstosuppresswarningsrelativetofieldaccessunqualified
unusedtosuppresswarningsrelativetounusedcodeanddeadcode
4.10.ImprovingJavacodequality
TheEclipseJavacompilerperformsmorechecksandanalysesthanaremandatedbytheJavaLanguageSpecification.Thisisdoneinordertohelpyoutoimprovethequalityof
yourJavacode.Sincedifferentusershavedifferentviewsofwhichwarningsareinteresting,thisbehaviorishighlyconfigurable.SeeJavaCompileErrors/WarningsPreferencesfor
availableoptions.
Somewarningsanderrorsshouldbeobviousandgenerallyvalidforeverybody.Insomecasesyoumaywanttoconfigurethecompilertomatchyourcodestyleandalsoyourquality
goals.Someanalysesaremosthelpfulifyoutosomedegreeadjustyourcodestyletomakeitbetteranalyzablebythecompiler.
Thepageslistedbelowgivesomebackgroundoncertainanalysesandhintsonhowtomakethebestuseofthem:
Usingnullannotations
Avoidingresourceleaks
Ensuringcompletenessofswitchstatements
4.10.1.Usingnullannotations
NullPointerExceptionisoneofthemostcommoncausesforfailureofJavaprograms.Inthesimplestcasesthecompilercandirectlywarnyouwhenitseescodelikethis:
Objecto=null
Strings=o.toString()
Withbranching/loopingandthrowingexceptionsquitesophisticatedflowanalysisbecomesnecessaryinordertofigureoutifavariablebeingdereferencedhasbeenassigneda
null/nonnullvalueonsomeorallpathsthroughtheprogram.
Duetotheinherentcomplexity,flowanalysisisbestperformedinsmallchunks.Analyzingonemethodatatimecanbedonewithgoodtoolperformancewhereaswholesystem
analysisisoutofscopefortheEclipseJavacompiler.Theadvantageis:analysisisfastandcanbedoneincrementallysuchthatthecompilercanwarnyoudirectlyasyoutype.
Thedownside:theanalysiscannot"see"whichvalues(nullornonnull)areflowingbetweenmethods(asparametersandreturnvalues).
Interproceduralnullanalysis
Thisiswherenullannotationscomeintoplay.Byspecifyingamethodparameteras@NonNullyoucantellthecompilerthatyoudon'twantanullvalueinthisposition.
Stringcapitalize(@NonNullStringin){
returnin.toUpperCase()//nonullcheckrequired
}
voidcaller(Strings){
if(s!=null)
System.out.println(capitalize(s))//precedingnullcheckisrequired
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 130/322
12/10/2015 Javadevelopmentuserguide
}
IntheveinofDesignbyContractthishastwosides:
1. It'sthecaller'sresponsibilitytoneverpassanullvalue,whichistobeensured,e.g.,byanexplicitnullcheck.
2. TheimplementorofmethodcapitalizeenjoystheguaranteethattheargumentinshallnotbenullandthusdereferencingwithoutanullcheckisOKhere.
Formethodreturnvaluesthesituationissymmetric:
@NonNullStringgetString(StringmaybeString){
if(maybeString!=null)
returnmaybeString//theabovenullcheckisrequired
else
return"<n/a>"
}
voidcaller(Strings){
System.out.println(getString(s).toUpperCase())//nonullcheckrequired
}
1. Nowtheimplementormustensurethatnullisneverreturned.
2. ConverselythecallernowenjoystheguaranteethatdereferencingthemethodresultwithoutcheckingisOK.
Availableannotations
TheEclipseJavacompilercanbeconfiguredtousethreedistinctannotationtypesforitsenhancednullanalysis(whichisdisabledbydefault):
@NonNull:nullisnotalegalvalue
@Nullable:nullvalueisallowedandmustbeexpected
@NonNullByDefault:typesinmethodsignaturesthatlackanullannotationareregardedasnonnull.
Annotations@NonNulland@Nullablearesupportedintheselocations:
Methodparameter
Methodreturn(syntacticallyamethodannotationisusedhere)
Localvariables
Fields
InJava8,morelocationscanbeannotatedwithnulltypeannotations
@NonNullByDefaultissupportedfor
Methodstoaffectalltypesinthismethod'ssignature
Types(classes,interfaces,enums)toaffectallmethodsinthetypebody
Package(viaafilepackageinfo.java)toaffectalltypesinthepackage
Note,thateventheactualqualifiednamesoftheseannotationsareconfigurable,butbydefaulttheonesgivenaboveareused(fromthepackageorg.eclipse.jdt.annotation).
Whenusing3rdpartynullannotations,pleaseensurethatthoseareproperlydefinedusingatleasta@Targetmetaannotation,becauseotherwisethecompilercannotdistinguish
betweendeclarationannotations(Java5)andtypeannotations(Java8).
Setupofthebuildpath
AJARwiththedefaultnullannotationsisshippedwithEclipseineclipse/plugins/org.eclipse.jdt.annotation_*.jar.ThisJARneedstobeonthebuildpathatcompiletimebutitisnot
necessaryatruntime(soyoudon'thavetoshipthistousersofyourcompiledcode).
StartingwithEclipseLuna,twoversionsofthisjarexist,onewithdeclarationannotationsforuseinJava7orbelow(version1.1.x)andonewithnulltypeannotationsforuseinJava
8(version2.0.x).
ForplainJavaprojectsthereisalsoaquickfixonunresolvedreferencesto@NonNull,@Nullable,or@NonNullByDefaultthataddsthesuitableversionoftheJARtothebuild
path:
ForOSGibundles/pluginspleaseaddoneofthefollowingentriestoyourMANIFEST.MF:
WhenusingnullannotationsinaJava7projectorbelow:
RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[1.1.0,2.0.0)"resolution:=optional
FornulltypeannotationsinaJava8projectpleaseuse:
RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[2.0.0,3.0.0)"resolution:=optional
Seealsothediscussioninthecorrespondingsectiononcompatibility.
Interpretationofnullannotations
ItshouldbeclearnowthatnullannotationsaddmoreinformationtoyourJavaprogram(whichcanthenbeusedbythecompilertogivebetterwarnings).Butwhatexactlydowe
wanttheseannotationstosay?Fromapragmaticpointofviewthereareatleastthreelevelsofwhatwemightwanttoexpresswithnullannotations:
1. Sporadichintstothereader(humanandcompiler)
2. Designbycontract:APIspecificationforsomeorallmethods
3. Fullspecificationusinganextendedtypesystem
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 131/322
12/10/2015 Javadevelopmentuserguide
For(1)youmaystartusingnullannotationsrightawayandwithoutreadingfurther,butyoushouldn'texpectmorethanalittlehinteverynowandthen.Theotherlevelsdeservesome
moreexplaining.
Designbycontract:APIspecification
AtfirstsightusingnullannotationsforAPIspecificationsintheveinofDesignbyContractonlymeansthatthesignaturesofallAPImethodsshouldbefullyannotated,i.e.,except
forprimitivetypeslikeinteachparameterandeachmethodreturntypeshouldbemarkedaseither@[email protected]
annotations,itisgoodtoknowthatinwelldesignedcode(especiallyAPImethods),@NonNullissignificantlymorefrequentthan@Nullable.Thusthenumberofannotationscanbe
reducedbydeclaring@NonNullasthedefault,usinga@NonNullByDefaultannotationatthepackagelevel.
Notethesignificantdifferencebetween@Nullableandomittinganullannotation:ThisannotationexplicitlystatesthatnullisOKandmustbeexpected.Bycontrast,noannotation
simplymeans,wedon'tknowwhat'stheintention.Thisistheoldsituationwheresometimesbothsides(callerandcallee)redundantlycheckfornull,andsometimesbothsides
wronglyassumethattheothersidewilldothecheck.ThisiswhereNullPointerExceptionsoriginatefrom.Withoutanannotationthecompilerwillnotgivespecificadvice,butwitha
@Nullableannotationeveryuncheckeddereferencewillbeflagged.
Withthesebasicswecandirectlymapallparameterannotationstopreconditionsandinterpretreturnannotationsaspostconditionsofthemethod.
Subtypingandoverriding
InobjectorientedprogrammingtheconceptofDesignbyContractneedstoaddressonemoredimension:subtypingandoverriding(inthesequeltheterm"override"willbeusedin
thesenseofthe@OverrideannotationinJava6:methodsoverridingorimplementinganothermethodfromasupertype).Aclientinvokingamethodlikethisone:
@NonNullStringcheckedString(@NullableStringin)
shouldbeallowedtoassumethatallimplementationsofthismethodfulfillthecontract.SowhenthemethoddeclarationisfoundinaninterfaceI1,wemustruleoutthatanyclass
CnimplementingI1providesanincompatibleimplementation.Specifically,itisillegalifanyCntriestooverridethismethodwithanimplementationthatdeclarestheparameteras
@NonNull.Ifwewouldallowthis,aclientmoduleprogrammedagainstI1couldlegallypassnullastheargumentbuttheimplementationwouldassumeanonnullvalueunchecked
dereferenceinsidethemethodimplementationwouldbeallowedbutblowupatruntime.Hence,a@Nullableparameterspecificationobligesalloverridestoadmitnullasan
expected,legalvalue.
Conversely,a@NonNullreturnspecificationobligesalloverridestoensurethatnullwillneverbereturned.
Therefore,thecompilerhastocheckthatnooverrideaddsa@NonNullparameterannotation(ora@Nullablereturnannotation)thatdidn'texistinthesupertype.
Interestingly,thereverseredefinitionsarelegal:addinga@Nullableparameterannotationora@NonNullreturnannotation(youmayconsidertheseas"improvements"ofthe
method,itacceptsmorevaluesandproducesamorespecificreturnvalue).
Byforcingsubclassestorepeatnullannotationsinanyoverridingmethods,thenullcontractofeachmethodcanbeunderstoodwithoutsearchingtheinheritancehierarchy.
However,insituationswhereaninheritancehierarchymixescodeofdifferentprovenanceitmaynotbepossibletoaddnullannotationstoallclassesatonce.Inthesesituationsthe
compilercanbetoldtotreatmethodswithmissingnullannotationsasifannotationsfromanoverriddenmethodwereinherited.Thisisenabledusingthecompileroptioninheritnull
annotations.Itispossiblethatamethodoverridestwomethodswithdifferentnullcontracts.Alsoanullnessdefaultcanbeapplicableatamethodwhichisinconflictwithan
inheritednullannotation.Thesecasesareflaggedasanerrorandtheoverridingmethodmustuseanexplicitnullannotationtoresolvetheconflict.
Relaxinga@NonNullparametertounspecified?
Ifinheritanceofnullannotationsisnotenabled,oneparticularsituationissafefromatypetheorypointofview,butmaystillindicateaproblem:Givenasupermethodthatdeclaresa
parameteras@NonNullandanoverridingmethodthatdoesnotconstrainthecorrespondingparameter(neitherbyanexplicitnullannotation,norbyanapplicable
@NonNullByDefault).
Thisissafebecauseclientsseeingthesuperdeclarationwillbeforcedtoavoidnullwhereasthetheoverridingimplementationsimplycannotleveragethisguaranteeduetothelack
ofaspecificationinthisspecificmethod.
Stillthismayleadtomisconceptionsbecauseitmaybeintendedthatthedeclarationinthesupertypeshouldapplyalsotoalloverrides.
Forthisreasonsthecompilerprovidesanoption'@NonNull'parameternotannotatedinoverridingmethod:
Enablingthiswarning/errorisusefulforforcingdeveloperstobeexplicitaboutthecontractofoverridingmethods.Ifnullshouldindeedbeacceptableitisgoodpracticetoadd
a@Nullableannotationtooverridethe@NonNullfromthesupermethod.
Disablingthiswarning/errorisusefulinscenariiofmixedcodeownership:itfacilitatestheuseoflegacyimplementations(withoutnullannotations)incombinationwithsuper
typesthathaveadoptedtheapproachofnullannotations.
Legacysupertypes
Thepreviousconsiderationsaddadifficultywhenannotatedcodeiswrittenasasubtypeofa"legacy"(i.e.,unannotated)type(whichmaybefroma3rdpartylibrary,thuscannot
bechanged).Ifyoureadthelastsectionverycarefullyyoumighthavenoticedthatwecannotadmitthata"legacy"methodisoverriddenbyamethodwitha@NonNullparameter
(sinceclientsusingthesupertypedon't"see"the@NonNullobligation).
Inthissituationyouwillbeforcedtoomitnullannotations(plansexisttosupportaddingannotationstolibrariesafterthefact,butnopromisecanbemadeyet,ifandwhensucha
featurewillbeavailable).
Cancelinganullnessdefault
Thesituationwillgettricky,ifasubtypeofa"legacy"typeresidesinapackageforwhich@NonNullByDefaulthasbeenspecified.Nowatypewithanunannotatedsupertype
wouldneedtomarkallparametersinoverridingmethodsas@Nullable:evenomittingparameterannotationsisn'tallowedbecausethatwouldbeinterpretedlikea@NonNull
parameter,whichisprohibitedinthatposition.That'swhytheEclipseJavacompilersupportscancellationofanullnessdefault:byannotatingamethodortypewith
@NonNullByDefault(false)anapplicabledefaultwillbecanceledforthiselement,andunannotatedparametersareagaininterpretedasunspecified.Now,subtypingislegalagain
withoutaddingunwanted@Nullableannotations:
classLegacyClass{
Stringenhance(Stringin){//clientsarenotforcedtopassnonnull.
returnin.toUpperCase()
}
}
@NonNullByDefault
classMyClassextendsLegacyClass{
//...methodswith@NonNulldefault...
@Override
@NonNullByDefault(false)
Stringenhance(Stringin){//wouldnotbevalidif@NonNullByDefaultwereeffectivehere
returnsuper.enhance(in)
}
}
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 132/322
12/10/2015 Javadevelopmentuserguide
Thecaseoffields
Nullannotationsworkbestwhenappliedinmethodsignatures(localvariablestypicallydon'tevenneedthese,butmayalsoleveragenullannotationsforbridgingbetween
annotatedcodeand"legacy"code).Insuchusagenullannotationsconnectthechunksofintraproceduralanalysisastoachievestatementsaboutglobaldataflows.Startingwith
EclipseKeplernullannotationscanalsobeappliedtofields,butherethesituationisslightlydifferent.
Considerafieldmarkedwith@NonNull:thisobviouslyrequiresthatanyassignmenttothefieldprovidesavaluethatisknownnottobenull.Additionally,thecompilermustbeable
toverifythatanonnullfieldcanneverbeaccessedinitsuninitializedstate(inwhichitstillhasthevaluenull).Ifitcanbeverifiedthateveryconstructorcompliestothisrule
(similarlyastaticfieldmusthaveaninitializer),theprogrambenefitsfromthesafetythatdereferencingthefieldcannevercauseaNullPointerException.
Thesituationismoredelicatewhenconsideringafieldmarked@Nullable.Suchafieldshouldalwaysbeconsideredasdangerousandtherecommendedwayofworkingwith
nullablefieldsis:alwaysassignthevaluetoalocalvariablebeforeworkingwithit.Usingalocalvariabletheflowanalysiscantellexactly,whetheradereferenceissufficiently
protectedbyanullcheck.Whenfollowingthisgeneralruleworkingwithnullablefieldsposesnoproblems.
Thingsgetmoreinvolvedwhenthecodedirectlydereferencesthevalueofanullablefield.Theproblemisthatanynullchecksthatthecodemayperformbeforethedereferencecan
easilybeinvalidatedbyoneofthese:
effectsviaaliasedreferences
sideeffectsofanothermethod
concurrency
Onecaneasilyseethatwithoutalsoanalyzingthreadsynchronization(whichisbeyondthecompiler'scapabilities)nonullcheckagainstanullablefieldwillevergrant100%safety
forasubsequentdereference.Soifconcurrentaccesstoanullablefieldispossible,thefield'svalueshouldneverbedirectlydereferenced,alwaysalocalvariableshouldbeused
instead.Evenifnoconcurrencyisinvolved,theremainingissuesposeachallengetoacompleteanalysisthatisharderthanwhatacompilercantypicallyhandle.
Flowanalysisvs.syntacticanalysis
Giventhecompilercannotfullyanalyzetheeffectsofaliasing,sideeffectsandconcurrency,theEclipsecompilerdoesnotperformanyflowanalysisforfields(otherthan
regardingtheirinitialization).Sincemanydeveloperswillconsiderthislimitationastoorestrictiverequiringtheuseoflocalvariableswheredevelopersfeelthattheircodeshould
actuallybesafeanewoptionhasbeenintroducedasatentativecompromise:
Thecompilercanbeconfiguredtoperformsomesyntacticanalysis.Thiswilldetectthemostobviouspatternslikethis:
@NullableObjectf
voidprintChecked(){
if(this.f!=null)
System.out.println(this.f.toString())
}
Withthegivenoptionenabledtheabovecodewillnotbeflaggedbythecompiler.Itisimportanttoseethatthissyntacticanalysisisnot"smart"inanyway.Ifanycodeappears
betweenthecheckandthedereferencethecompilerwillcowardly"forget"theinformationofthepreviousnullcheck,withouteventryingtoseeiftheintermediatecodecouldperhaps
beharmlessaccordingtosomecriteria.Thuspleasebeadvised:wheneverthecompilerflagsadereferenceofanullablefieldasunsafealthoughthehumaneyemayseethatnull
shouldnotoccur,pleaseeitherrewriteyourcodetocloselyfollowtherecognizedpatternshownabove,or,evenbetter:usealocalvariabletoleverageallthesophisticationofflow
analysis,whichsyntacticanalysiswillneverattain.
BenefitsofDesignbyContract
UsingnullannotationsinthestyleofDesignbyContractasoutlinedabove,helpstoimprovethequalityofyourJavacodeinseveralways:Attheinterfacebetweenmethodsitis
madeexplicit,whichparameters/returnstolerateanullvalueandwhichonesdon't.Thiscapturesdesigndecisions,whicharehighlyrelevanttothedevelopers,inawaythatisalso
checkablebythecompiler.
Additionally,basedonthisinterfacespecificationtheintraproceduralflowanalysiscanpickupavailableinformationandgivemuchmorepreciseerrors/warnings.Without
annotationsanyvalueflowingintooroutofamethodhasunknownnullnessandthereforenullanalysisremainssilentabouttheirusage.WithAPIlevelnullannotationsthenullness
ofmostvaluesisactuallyknown,andsignificantlyfewerNPEswillgounnoticedbythecompiler.However,youshouldbeawarethatstillsomeloopholesexist,whereunspecified
valuesflowintotheanalysis,preventingacompletestatementwhetherNPEscanoccuratruntime.
Completespecificationusinganextendedtypesystem
Thesupportfornullannotationshadbeendesignedinawaythatshouldbecompatibletoafutureextension.ThisextensionhasbecomepartoftheJavalanguageastype
annotations(JSR308),whichhavebeenintroducedinJava8.JDTsupportstoleveragethenewconceptfornulltypeannotations.
Compilermessagesexplained
Semanticdetailsofannotationbasednullanalysisarepresentedhere,byexplainingtherulesthatthecompilerchecksandthemessagesitissuesuponviolationofarule.
Onthecorrespondingpreferencepagetheindividualrulescheckedbythecompileraregroupedunderthefollowingheadings:
Violationofnullspecification
Asspecificationviolationwehandleanysituationwhereanullannotationmakesaclaimthatisviolatedbytheactualimplementation.Thetypicalsituationresultsfromspecifyinga
value(local,argument,methodreturn)as@NonNullwhereastheimplementationactuallyprovidesanullablevalue.Hereanexpressionisconsideredasnullableifeitheritis
staticallyknowntoevaluatetothevaluenull,orifitisdeclaredwitha@Nullableannotation.
Secondly,thisgroupalsocontainstherulesformethodoverridingasdiscussedabove.Hereasupermethodestablishesaclaim(e.g.,thatnullisalegalargument)whileanoverride
triestoevadethisclaim(byassumingthatnullisnotalegalargument).Asmentionedevenspecializinganargumentfromunannotatedto@NonNullisaspecificationviolation,
becauseitintroducesacontractthatshouldbindtheclient(tonotpassnull),butaclientusingthesupertypewon'tevenseethiscontract,sohedoesn'tevenknowwhatis
expectedofhim.
Thefulllistofsituationsregardedasspecificationviolationsisgivenhere.Itisimportanttounderstandthaterrorsinthisgroupshouldneverbeignored,becauseotherwisethe
entirenullanalysiswillbeperformedbasedonfalseassumptions.Specifically,wheneverthecompilerseesavaluewitha@NonNullannotationittakesitforgrantedthatnullwillnot
occuratruntime.It'stherulesaboutspecificationviolationswhichensurethatthisreasoningissound.Thereforeitisstronglyrecommendedtoleavethiskindofproblemconfigured
aserrors.
Conflictbetweennullannotationsandnullinference
Alsothisgroupofruleswatchesovertheadherencetonullspecifications.However,herewedealwithvaluesthatarenotdeclaredas@Nullable(northevaluenullitself),butvalues
wheretheintraproceduralflowanalysisinfersthatnullcanpossiblyoccuronsomeexecutionpath.
Thissituationarisesfromthefactthatforunannotatedlocalvariablesthecompilerwillinferwhethernullispossibleusingitsflowanalysis.Assumingthatthisanalysisisaccurate,
ifitseesaproblemthisproblemhasthesameseverityasdirectviolationsofanullspecification.Therefore,itisagainstronglyrecommendedtoleavetheseproblemsconfiguredas
errorsandnottoignorethesemessages.
Creatingaseparategroupfortheseproblemsservestwopurposes:todocumentthatagivenproblemwasraisedwiththehelpoftheflowanalysis,and:toaccountforthefactthat
thisflowanalysiscouldbeatfault(becauseofabugintheimplementation).ForthecaseofanacknowledgedimplementationbugitcouldinexceptionalsituationsbeOKto
suppressanerrormessageofthiskind.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 133/322
12/10/2015 Javadevelopmentuserguide
Giventhenatureofanystaticanalysis,theflowanalysismayfailtoseethatacertaincombinationofexecutionpathsandvaluesisnotpossible.Asanexampleconsidervariable
correlation:
Stringflatten(String[]inputs1,String[]inputs2){
StringBuffersb1=null,sb2=null
intlen=Math.min(inputs1.length,inputs2.length)
for(inti=0i<leni++){
if(sb1==null){
sb1=newStringBuffer()
sb2=newStringBuffer()
}
sb1.append(inputs1[i])
sb2.append(inputs2[i])//warninghere
}
if(sb1!=null)returnsb1.append(sb2).toString()
return""
}
Thecompilerwillreportapotentialnullpointeraccessattheinvocationofsb2.append(..).Thehumanreadercanseethatthereisnoactualdangerbecausesb1andsb2actually
correlateinawaythateitherbothvariablesarenullorbotharenotnull.Atthelineinquestionweknowthatsb1isnotnull,hencealsosb2isnotnull.Withoutgoingintothedetails
whysuchcorrelationanalysisisbeyondthecapabilityoftheEclipseJavacompiler,pleasejustkeepinmindthatthisanalysisdoesn'thavethepowerofafulltheoremproverand
thereforepessimisticallyreportssomeproblemswhichamorecapableanalysiscouldpossiblyidentifyasfalsealarms.
Ifyouwanttobenefitfromflowanalysis,youareadvisedtogivealittlehelptothecompilersoitcan"see"yourconclusions.Thishelpcanbeassimpleassplittingtheif(sb1==
null)intotwoseparateifs,oneforeachlocalvariable,whichisaverysmallpricetopayforthegainthatnowthecompilercanexactlyseewhathappensandcheckyourcode
accordingly.Morediscussiononthistopicwillfollowbelow.
Uncheckedconversionfromnonannotatedtypeto@NonNulltype
Thisgroupofproblemsisbasedonthefollowinganalogy:inaprogramusingJava5genericsanycallstopreJava5librariesmayexposerawtypes,i.e.,applicationsofageneric
typewhichfailtospecifyconcretetypearguments.Tofitsuchvaluesintoaprogramusinggenericsthecompilercanaddanimplicitconversionbyassumingthattypearguments
werespecifiedinthewayexpectedbytheclientpartofthecode.Thecompilerwillissueawarningabouttheuseofsuchaconversionandproceeditstypecheckingassumingthe
library"doestherightthing".Inexactlythesameway,anunannotatedreturntypeofalibrarymethodcanbeconsideredasa"raw"or"legacy"type.Againanimplicitconversioncan
optimisticallyassumetheexpectedspecification.Againawarningisissuedandanalysiscontinuesassumingthatthelibrary"doestherightthing".
Theoreticallyspeaking,alsotheneedforsuchimplicitconversionsindicatesaspecificationviolation.However,inthiscaseitmaybe3rdpartycodethatviolatesthespecification
whichourcodeexpects.Or,maybe(aswehaveconvincedourselvesof)some3rdpartycodedoesfulfillthecontract,butonlyfailstodeclareso(becauseitdoesn'tusenull
annotations).Insuchsituationswemaynotbeabletoexactlyfixtheproblemfororganizationalreasons.
@SuppressWarnings("null")
@NonNullFoofoo=Library.getFoo()//implicitconversion
foo.bar()
TheabovecodesnippetassumesthatLibrary.getFoo()returnsaFoowithoutspecifyinganullannotation.Wecanintegratethereturnvalueintoourannotatedprogramby
assignmenttoa@NonNulllocalvariable,whichtriggersawarningregardinganuncheckedconversion.ByaddingacorrespondingSuppressWarnings("null")tothisdeclarationwe
acknowledgetheinherentdangerandaccepttheresponsibilityofhavingverifiedthatthelibraryactuallybehavesasdesired.
Tipsformakingcodebetteranalyzable
Ifflowanalysiscannotseethatavalueisindeednotnull,thesimpleststrategyisalwaystoaddanewscopedlocalvariableannotatedwith@NonNull.Then,ifyouareconvinced
thatthevalueassignedtothislocalwillneverbenullatruntimeyoucanuseahelpermethodslikethis:
static@NonNull<T>TassertNonNull(@NullableTvalue,@NullableStringmsg){
if(value==null)thrownewAssertionError(msg)
returnvalue
}
@NonNullMyTypefoo(){
if(isInitialized()){
MyTypecouldBeNull=getObjectOrNull()
@NonNullMyTypetheValue=assertNonNull(couldBeNull,
"valueshouldnotbenullbecauseapplication"+
"isfullyinitializedatthispoint.")
returntheValue
}
returnnewMyTypeImpl()
}
NotethatbyusingtheaboveassertNonNull()methodyouareacceptingtheresponsibilitythatthisassertionwillalwaysholdatruntime.Ifthatisnotwhatyouwant,annotated
localvariableswillstillhelptonarrowdownwhereandwhytheanalysisseesapotentialfornullflowingintoacertainlocation.
Tipsforadoptingnullannotations
AtthetimeofreleasingtheJDTversion3.8.0,collectingadviceforadoptingnullannotationsisstillworkinprogress.Forthatreasonthisinformationiscurrentlymaintainedinthe
Eclipsewiki.
4.10.2.Usingnulltypeannotations
StartingwithJava8,nullannotationscanbeusedinanewandmorepowerfulway,becausethenewconceptof"typeannotations"(JSR308)supportstheuseofannotationsasan
extensiontothetypesystem.
Technically,thisisdeterminedbytwonewelementsintheenumjava.lang.annotation.ElementType:TYPE_USEandTYPE_PARAMETER.Notably,whensaying
@Target(ElementType.TYPE_USE)theannotationthusmarkedcanbeattachedbasicallytoallusagesofatype.
ByinterpretingnullannotationsaspartofthetypesystemweinterpreteachclassorinterfaceCninthesystemasintroducingtwodistincttypes:"@NonNullCn"and"@Nullable
Cn".TheformertypecontainsallinstancesofCnwhereasthelattertypeadditionallycontainsthevaluenull.Thisimpliesthat@NonNullCnisasubtypeof@NullableCnwithall
regularconsequencesregardingassignability.Soideallyforeveryvalueinaprogramwewillknowifitcanbenull(andmustbecheckedbeforedereference)ornot.Theunannotated
typewillbeconsideredalegacytypejustlikerawtypesarelegacytypessincetheintroductionofgenerics:awayforinterfacingwitholdcode,tobeflaggedwithwarningsabout
uncheckedconversions.Ifwesystematicallyavoidsuchlegacytypes,thenthecompilercanrigorouslyflageveryunsafeusage.
Inordertoachievecompletenessofnullanalysis,checksregardingnulltypeannotationshavebeenintegratedwithalltypecheckingtasksofthecompiler(activeifnullannotations
areenabled).
UsersmigratingfromnullannotationsinpreviousversionstoJava8stylenulltypeannotationsareadvisedtocheckthesectionaboutcompatibility.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 134/322
12/10/2015 Javadevelopmentuserguide
Generics
Perhapsthemainadvantageoftypeannotationsfornullanalysisistheabilitytoannotatetheparametersandargumentsofgenericclassesandinterfaces.Programmersonlyusing
genericclassesmaydirectlyskiptothesectionontypeargumentsbutdesignersofgenericclassesshouldtakethetimetounderstandthedifferentimplicationsofannotatingthese
elements:
typeparameters
typevariables
typearguments
Typeparameters
Agenericclass,interfaceormethodmaydeclareoneormoretypeparameters.Technicallythesearedeclarations,andhenceitwasamereoversightthatthesecannotbeannotated
inJava5.InJava8anannotationcandeclare@Target(ElementType.TYPE_PARAMETER)tobeapplicableinthisposition.JDT'snulltypeannotations@NonNulland@Nullableare
declaredwith@Target({TYPE_USE}),whichincludesusageontypeparameterdeclarations.
Withrespecttonulltypeannotations,eachtypeparametercanbespecifiedatoneoftheselevels:
unconstrained
thetypeparameterdoesnotimposeanynullnessconstraintsontheargumentsthataclientmysubstituteforthetypeparameter.
constrainedbyanupperbound
thetypeparameterhasanextendsclausethatspecifiesminimalnullnessrequirementsontypeargumentsprovidedbyclients
exactlyspecified
thetypeparameterrestrictsusagetotypesofexactlyoneparticularnullness
Constrainingatypeparameterviaanupperboundreliesonthefactthateachtype' @NonNullCn'isasubtypeofthecorrespondingtype' @NullableCn'.Hence,a@Nullable
upperbounddoesnotimposeanyrestriction,whereasa@NonNullupperboundprohibitsthesubstitutionbya@Nullabletypeargument:
//declarations:
classC0<T0extends@NullableObject>{}//meaningless,noconstraintimposed
classC1<T1extends@NonNullObject>{}
...
//usage:
C1<@NonNullString>c1String//legal
C1<@NullableString>c1String//illegal
Forexactspecificationanullannotationmaybeattachedtothetypeparameterdeclarationitself,whichisinterpretedasdefiningbothanupperandalowerbound.Inotherwords,
onlytypeswiththeexactsamenulltypeannotationarelegalastypearguments:
//declaration:
classC2<@NullableT2>{}
...
//usage:
C2<@NonNullString>c2String//illegal
C2<@NullableString>c2String//legal
Giventheasymmetry,thatinJavaatypeparametermaydeclareonlyupperboundsbutnolowerbounds,thefollowingthreestylescanberecommended:
Usea@NonNullupperboundforconstrainingtypeargumentstononnulltypes.
Directlyspecifyatypeparameteras@Nullableforconstrainingtypeargumentstonullabletypes.
Useanunconstrainedtypeparametertosupporttypeargumentsofeithernullness.
Typevariables
Withinthescopeofagenericdeclaration(class,interfaceormethod),thenameofatypeparametercanbeusedasatypevariable,i.e.,aplaceholderforatypethatisnotknownat
thispoint.
Atypevariablewilltypicallybeusedwithout(further)nullannotations,whichimpliesthattheannotationsfromthetypeparameterdeclarationwillapplyasdetailedbelow.Insome
situations,however,itisusefultoannotateanindividualuseofatypevariable.Asanexampleconsiderthelibrarymethodjava.util.Map.get(Object),whichshouldactuallybe
annotatedlikethis:
@NullableVget(Objectkey)
BythisdeclarationwewouldindicatethatthereturntypeisthenullablevariantofwhatevertypeVmayrepresent.Inotherwords,anullannotationontheuseofatypevariable
overridesanyothernullinformationthatwouldotherwiseapplytothistype.Inparticularanynullannotationonthecorrespondingtypeparameterdeclaration(oritsbound)is
overriddenbyanullannotationinthisposition.
Ontheotherhand,whenusingatypevariablewithoutimmediatenullannotationsthefollowingrulesapplydependingonthedeclarationofthecorrespondingtypeparameter:
Atypevariablecorrespondingtoatypeparameterwitha@NonNullupperbounddenotesatypethatisknowntobenonnull.
classC1<T1extends@NonNullNumber>{
intconsume(T1t){
returnt.intValue()//OKsinceT1isknowntobenonnull
}
T1provide(){
returnnull//NOTOKsinceT1requiresnonnull
}
}
Atypevariablecorrespondingtoatypeparameterspecifiedas@Nullabledenotesatypethatisknowntobenullable.
classC2<@NullableT2extendsNumber>{
intconsume(T2t){
returnt.intValue()//NOTOKsinceT2isknowntobenullable
}
T2provide(){
returnnull//OK:returningnullislegal
}
}
Atypevariablecorrespondingtoanunconstrainedtypeparameterrequirespessimisticcheckinginordertoguaranteesafetywithalllegalsubstitutions:thistypecanneitherbe
assumedtobenullablenornonnull.
classC<TextendsNumber>{
intconsume(Tt){
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 135/322
12/10/2015 Javadevelopmentuserguide
returnt.intValue()//NOTOKsinceTcouldbenullable
}
Tprovide(){
returnnull//NOTOKsinceTcouldrequirenonnull
}
}
Thelastpointmaylooksurprisingatfirst,butpleaseseethatanunconstrainedtypeparameterimpliesthatwemaynotassumeanythingaboutthenullnessofthetyperepresented
bythecorrespondingtypevariable.Evenmore:wemustactivelysupportnullableandnonnulltypes.Ontheotherhandthissimplyextendstheexistingrulethattheonlytypebeing
compatiblewithanunboundedtypevariableisthetypevariableitself.Toexplainthissituationinthecontextofnullanalysis,thecompilerwillraisethefollowingerroragainstthe
returninprovide():
Nulltypemismatch(typeannotations):'null'isnotcompatibletothefreetypevariable'T'
Byenforcingthisdefensivestrategyregardingunconstrainedtypeparametersweobtainthebenefitofallowingclientstofreelychoosetherulesforaparticulargenericinstantiation,
aswillbeshownnext.
Typearguments
Wheninstantiatingagenerictypeorwheninvokingagenericmethod,theconstraintsputforwardbythetypeparametermustbeobserved.Hence,whenaproviderofagenerictype
ormethodspecifiedtherequirednullness,thismustbeobeyedandthecompilerwillflaganyviolations.
When,ontheotherhand,atypeparameterdoesnotimposeanyrestrictions,aclientmayfreelychoosethenullnessofhistypearguments:
intprocessWithoutNulls(@NonNullList<@NonNullInteger>ints){
intresult=0
for(inti=0i<ints.size()i++){
Integerelement=ints.get(i)
result+=element.intValue()//OK:listelementisknowntobenonnull
ints.set(i,null)//NOTOK:listdoesnotacceptnullvalue
}
returnresult
}
intprocessWithNulls(@NonNullList<@NullableInteger>ints){
intresult=0
for(inti=0i<ints.size()i++){
Integerelement=ints.get(i)
result+=element.intValue()//NOTOK:listelementcanbenull
ints.set(i,null)//OK:listacceptsnullvalue
}
returnresult
}
Inference
Withnulltypeannotationsaffectingtypearguments,thelanguagefeaturesonemorelocationamenabletoinference:duringtypeinferencefortheinvocationofagenericmethod
(lambdaexpressionetc.),typeinferenceshylyattemptstoalsoinfertheappropriatenulltypeannotations.Example:
<T>Tcheck(Tin){returnin}
voidtest(@NonNullList<@NullableString>someStrings){
@NonNullList<@NullableString>checked
checked=check(someStrings)//inferringtypesforthisinvocation
...
}
Inthistrivialexample,inferencewillindeedinstantiatethegenericparameter<T>to@NonNullList<@NullableString>.Morecomplexscenariosareinferred,too,butnoguarantee
ismade,thatapossiblesolutionwillalwaysbefound.Incaseinferencefailstoinfersuitablenulltypeannotations,usersareadvisedtoreverttoexplicitlyspecifytypearguments
evenofagenericmethodinvocation.
Morelocations
Castandinstanceof
Syntactically,typeannotationscanbeusedalsoincastsandinstanceofexpressions.Fornullannotations,however,thishaslimitedvalue.
Castingtoanullannotatedtypeisalwaysanuncheckedcastbecausethecompilerisnotallowedtoinsertruntimechecksthatwouldmakethecastmeaningful.Ifaruntimecheck
isdesired,pleaseconsiderusingasmallhelperfunctionlike:
static@NonNull<T>TcastToNonNull(@NullableTvalue,@NullableStringmsg){
if(value==null)thrownewNullPointerException(msg)
returnvalue
}
Castsaffectingthetypeargumentsofagenerictypewillalwaysbeuncheckedcastsduetoerasure.
instanceofcheckswithnulltypeannotationsarenotmeaningful.Hencethecompilerflagsthisasillegalusageofanulltypeannotation.
Locationsthatarenonnullbydefinition
Syntactically,typeannotationscanalsobeusedfor
allocationexpressions
methodreceiver(pseudoargumentbythenameofthis)
catchparameter
Ineachoftheseconstructs,thetypeisnonnullbydefinition.Henceanulltypeannotationinoneofthesepositionsisflaggedasillegaluse.Thisdoesn't,however,restricttheuseof
nulltypeannotationsontypeargumentsofthegiventype.
Compatibility
Migratingfromdeclarationannotationstotypeannotationshasafewunavoidableimplications,regardingthesyntax,regardingprojectconfigurationandregardingthesemantics.
Syntax
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 136/322
12/10/2015 Javadevelopmentuserguide
FortwoconstructstheJLSintroducesasyntacticchange:
DeclarationAnnotations(Java7orbelow) TypeAnnotation(Java8)
@NonNullString[] String@NonNull[]
@NonNulljava.lang.String java.lang.@NonNullString
Inbothcasesthenewsyntaxhasbeenintroducedtoprovidemoreoptions.
Forarraysatypeannotationbeforetheleafelementtypewillnowdenoteanarraywhoseindividualcellshavethegivennullnesshere:cellscannotbenull.InJava7andbelowthe
samesyntaxexpressedapropertyofthecorrespondingvariableandhencecapturedthenullnessofthearrayitself.ToexpressthesameusingJava8typeannotations,viz.thatthe
arrayitselfcanorcannotbenull,thetypeannotationisplacedbeforethesquarebracketsdenotingthearraydimensions.Thisimpliesthattheoldsyntaxisstillvalid,butitsmeaning
haschanged:
//annotatedleaftype:
@NonNullObject[]o1
o1=null//OK
o1=newObject[1]
o1[0]=null//NOTOK
...
//annotatedarraytype:
Object@NonNull[]o2
o2=null//NOTOK
o2=newObject[1]
o2[0]=null//OK
...
//multidimensionalarray:
Object@NonNull[]@Nullable[]o3
o3=null//NOTOK,outerarrayisnonnull
o3=newObject[1]@Nullable[]
o3[0]=null//OK,innerarrayisnullable
Unfortunately,checkingproperinitializationofanarraywithnonnullcontentisbeyondthecapabilitiesofJDT'sstaticanalysis.
Forqualifiedtypenamesthetypeannotationmustbeplaceddirectlyprecedingtheactualtypename.Thiswayitispossibletogivedifferenttypeannotationsforinnerclassesand
theirenclosinglikeinorg.project.@[email protected],however,isnotusefulfornullannotations,becausetheenclosingofanonstaticinner
classisbydefinitionalwaysnonnull.Usersofnulltypeannotationsonlyneedtounderstandthattheoldsyntaxforthiscaseisillegalfortypeannotationsandhowtoconvertthis
intolegalJava8code(seethetableabove).
Projectconfiguration
Properlydesignedannotationtypescanbedistinguishedbylookingattheir@Targetdeclaration(theuseofnullannotationslackinga@Targetdeclarationisdiscouraged).Tosupport
bothstylesofannotations,JDThaspublishedamajorupdateoftheannotationbundleorg.eclipse.jdt.annotation:Versions1.1.xareoldstyledeclarationannotationsversions
2.0.0andonwardaretypeannotations.Byincreasingthemajorversionanincompatibilityissignaled.Usersareadvisedtoreferencethislibrarywithanexplicitversionrange,either
[1.1.0,2.0.0)fordeclarationannotationsor[2.0.0,3.0.0)fortypeannotations.
Theexactconfigurationdependsofcourseontheflavorofproject:
PlainJava
JDTcontinuestoofferaquickfixforcopyingtheannotationlibraryintotheproject.Theversionwillbedeterminedbythecompliancesettingsoftheproject.
Maven
Bothversionsoftheannotationbundlewillbepublishedtorepo.eclipse.org,fromwheretheycanbeconsumedusingtheregularmavenmechanisms:besuretospecify
thecorrectversionspecifying<scope>compile</scope>isrecommendedforthisdependency.
OSGi/Eclipse
WhendevelopingOSGibundles/Eclipsepluginstheversionrangeshouldbespecifiedasmentionedabove.Unfortunately,OSGidoesn'tsupportaconceptofcompiletime
dependencies.ThePDEspecificmechanisminfilebuild.propertiesisproblematicbecauseitdoesn'tsupportspecifyingaversionrange.Thusthebestapproximationof
thedesiredsemanticsistouseaRequireBundledependency.qualifiedwithresolution:=optionalinordertoavoidforcingthisdependencyontheruntime:
RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[2.0.0,3.0.0)"resolution:=optional
SemanticsNonNullByDefault
Whilethefundamentalsemanticsofnullannotationremainsunchanged,theannotation@NonNullByDefaulthasbeenchangedslightly:
Thisannotationcannowaffectmorelocations.
Thelocationstobeaffectedcanbefinetunedusingthevaluepropertyoftheannotation(seealsotheenumDefaultLocation).
Asaconsequence,thenotationforcancelingadefaultfromanouterscopehasbeenchanged,too:
DeclarationAnnotations(Java7orbelow) TypeAnnotation(Java8)
@NonNullByDefault(false) @NonNullByDefault({})
AlthoughtheJava8variantof@NonNullByDefaultaffectsmorelocations,twonoteworthyexceptionsexist(asspecifiedinDefaultLocation):
Wildcardsandtheuseoftypevariablesarealwaysexcludedfrom@NonNullByDefault.
Bythisrule,typevariablesandwildcardsretaintheirintendedpropertiesas"unknowns"alsointermsofnullness,evenwhentheyappearinthecontextof@NonNullByDefault.
Compilermessagesexplained
Inadditiontocompilermessagesofthepreviousversionthefollowingmessagesmaybeissued,ifnulltypeannotationsareenabledforanalysis:
Generalnulltypemismatch
Nulltypemismatch(typeannotations):required'X'butthisexpressionhastype'Y'
Inanassignmentcontextnulltypeannotationsdon'tmatch.Notethatthemismatchmayrelatetoanydetailofthetype(typeargument,arrayelement),notnecessarilytothe
maintype.
Allmismatchesdetectedbasedontypeannotationsareprefixedwith"Nulltypemismatch(typeannotations)".
Variousexpressions
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 137/322
12/10/2015 Javadevelopmentuserguide
Potentialnullpointeraccess:arrayelementmaybenull
Anarrayelementisdereferenced,wherethearraytypedeclaresitselementsas@Nullable.
Potentialnullpointeraccess:thisexpressionhasa'@Nullable'type
Anyexpressionatthelefthandsideofadothasatypethatisdeclaredtobenullable.
Redundantnullcheck:comparing'@NonNullX'againstnull
Anarbitraryexpressionknowntohavea@NonNulltypeisunnecessarilybeingcomparedagainstnull.
Uncheckedconversions
Nulltypesafety(typeannotations):Theexpressionoftype'X'needsuncheckedconversiontoconformto'@NonNullX'
Avalueofanunannotatedtypeisbeingassignedtoavariableofanannotatedtype.Notethatthemismatchmayrelatetoanydetailofthetype(typeargument,array
element),notnecessarilytothemaintype.
Nulltypesafety:UncheckedcastfromXto'@NY'
Avalueiscastedtoanullannotatedtype,wherethenullnessisnotcheckedatruntimebythecast.
Problemsspecifictogenerics
Nullconstraintmismatch:Thetype'X'isnotavalidsubstituteforthetypeparameter'T'
Herethetypeparameter<T>hasaconstraintinoneoftheformsmentionedabove.TheactualtypeargumentX,however,doesn'tconformtothisconstraint.
Thisnullnessannotationconflictswitha'@N'annotationwhichiseffectiveonthesametypeparameter
Anullannotationonaboundofatypeparameterconflictswithanothernullannotationonanotherboundoronthetypeparameteritself.
Nulltypemismatch(typeannotations):''null''isnotcompatibletothefreetypevariable'T'
Anattemptismadetoassingnulltoavariabletypedtoanunconstrainedtypevariable,seethesectionontypevariables
Nulltypemismatch(typeannotations):required'T'butthisexpressionhastype'@NullableT',where'T'isafreetypevariable
Anattemptismadetoassignavalueofanullabletypetoavariabletypedtoanunconstrainedtypevariabled,seethesectionontypevariables
Contradictorynullannotations:methodwasinferredas'Tfoo(X)',butonlyoneof'@NonNull'and'@Nullable'canbeeffectiveatanylocation
Typeinferenceforagenericmethodinvocationhasproducedasignatureinwhichcontradictorynullannotationsclashonthesameelement.
Lambdaexpressionsandmethodreferences
Foranymismatchesinnullannotationsaffectinglambdaexpressionsormethodreferencesthecorresponding"descriptor"ismentioned(thesingleabstractmethodbeing
implementedbythelambda/methodreference).Thisisusefullforfindingtheoriginofanullannotationthatisnotexplicitatthecurrentexpression.
4.10.3.Usingexternalnullannotations
Nullannotations,orevenbetter,nulltypeannotationscansignificantlyreduce(ideally:eliminate)thedangerofNullPointerExceptionthrownatprogramruntime.Unfortunately,the
APIofmanylibrariesdoesnotyetconsistentlyspecifywherenullisallowedandwhereitisn't.Thiscanbeamajorsourceofincompletenessinthisendeavor.Inordertofillthis
gap,startingwithEclipse4.5(Mars),JDTsupportstheconceptofexternalannotations,whichmeansthatnullannotationscanbespecifiedinseparatefileswithoutmodifyingthe
originallibrary.Ifyouattachsuchexternalnullannotationstoagivenlibrary,JDTwillthenconsidertheseannotationsforitsstaticnullanalysis.
Thishelppagedescribes
thestructureofexternalannotations
configuringaprojecttouseexternalannotations
interactivelycreatingexternalannotations
inspectingexternalannotations
differencesbetweendeclarationannotationsandtypeannotations
Structureofexternalannotations
Externalannotationscanbeprovidedasadirectorytree,whoseleavesaretextfileswithextension.eea("EclipseExternalAnnotations").Inthisstructure,eachdirectory
correspondstoaJavapackage,andeach.eeafilecorrespondstoaJavatype(class,interfaceetc.).
Optionally,theabovestructurecanbepackedinasinglezipfilewithextension.zipor.jar.
Theexactformatof.eeatextfileshasbeendesignedwithslightbiastowardsprocessingbytools.Still,thesefilesareamenabletostoring,comparingandmergingusingany
versioncontrolsystem.Theformatisbasedonsignaturesasdefinedin JVMS4.7.9.1.
Configuringaprojecttouseexternalannotations
Caveat:Whendifferentprojectsreferringtothesamelibraryhavedifferentconfigurationswithrespecttoexternalannotations,theUIsupportdescribedbelow
(commandAnnotateandJavadochovers)caneasilygetconfused:Whenlookingatagivenlibraryclass,JDTmaynotknowwhichprojecttheuseriscurrentlyworking
on,producingunexpectedresults.Whilehopefullythiswillbeimprovedinafutureversion,forthetimebeingusersareadvisedtousethesameexternalannotation
locationforallprojectsreferringtothesamelibrary.Ashared("common")baseprojectwilltypicallybeagoodchoiceforhostingexternalannotations.
JavaRuntimeEnvironments
ExternalannotationscanbedirectlyattachedtoeachJREconfiguredinthecurrentworkspace.Forthispurpose,pleaseusetheInstalledJREspreferencepageandclickEditfor
detailsoftheselectedJRE.AfterselectingoneormoreJarfilescontributedbythegivenJREinstallation,clickExternalAnnotationstoopenanewdialog,whereeitheradirectory
orazipfilecanbeselectedastheexternalannotationlocationfortheselectedjar(s).
Alternatively,youmayselectthepropertiesofaspecificJREboundintheJavaBuildPathofaspecificproject.Pleasenote,thatattachingexternalannotationstoindividualjarsofa
JREalwaysaffectstheworkspacepreference,evenifaccessedviatheproject'sbuildpath.Theonlywaytodefineaprojectspecificlocationforexternalannotationlocationfora
JREisviathedirectchildExternalannotations:ofthetoplevelnodecalledJRESystemLibrary,butnote,thatprojectspecificlocationsarenotrecommended,seethe"Caveat"
above.
OtherClasspathContainers
Dependingonthebuildtechnologyinuse,projectsmayhaveadditionalclasspathcontainerslikePluginDependenciesorMavenDependencies.Forthesecontainers,theonly
optioncurrentlyistospecifytheexternalannotationlocationviaeachprojectsbuildpath.Inthiscaseusersareadvisedtomanuallyensurethatthesamelocationisusedforall
projectsoftheworkspace,seethe"Caveat"above.
OtherLibraries
Foranyotherlibraries(jars)explicitlyreferencedfromtheJavaBuildPathofaproject,externalannotationscanbeattachedseparatelyintheLibrariespageoftheproject'sbuild
path.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 138/322
12/10/2015 Javadevelopmentuserguide
Creatingexternalannotations
Prerequisites:Externalannotationsrequirealibrarywithsourceattachment.Additionally,annotationbasednullanalysismustbeenabledforthecurrentproject,anexternal
annotationlocationmustbedefinedforthelibraryandthatlocationmustbeadirectory(notazipfile)withintheworkspace.
Afternavigatingtothedesiredclass,youmayselectthetype(methodparameterormethodreturntype)thatshouldbeaffectedbyanannotation,andinvokethenewcommand
Annotate(availableviacontextmenuandbydefaultboundtoCtrl1).SimilartoquickassistsinaJavasourcecodeeditor,thiscommandwillofferproposalsapplicableatthe
currentlocation.Forexternalannotations,thethreeoptionsare:
Annotateas'@NonNullSomeType'
Annotateas'@NullableSomeType'
Removenullnessannotationfromtype'SomeType'
Forobviousreasons,exactly2ofthesethreeproposalsareofferedatanysuitablelocation.Behindthescenesthiscommandwillcreateand/orupdatean.eeafilecorrespondingto
thecurrentclass.Thenewannotationwillthenberespectedbythecompiler:ErrorsandwarningsinanopeneditorwillbeupdatedimmediatelyTheProblemsviewwillbeupdated
whenaffectedclassesarerecompiled.
Becareful:Whenattachingexternalannotationstoalibrary,keepinmindthatyouaredefininganewcontract,thatwillthenbeusedtocheckyourprogramagainst.
Thecompilerwill,however,notcheckthelibrary,whetheritactuallyconformstothiscontract.Bycarelesslymarking,e.g.,areturntypeas@NonNullyouletthe
compileradviseyoutoremovenullchecksagainstreturnvaluesfromthegivenmethod.Ifthelibrarydoesreturnnullinanysituation,thisnullwillhityouunguarded.
Beforeaddinganannotation,makesureitisbackedbyfacts,like,e.g.:
explicitmentioninJavadoc,e.g.,whena@returnspecificationsays:"...ornullwhen...".
anexplicitnullcheckofamethodparameter,whichdoesnotthrowanexception(implyingthatnullisaccepted@Nullableparameter)
uncheckdereferenceofamethodparameter(implyingthatnullisnotaccepted@NonNullparameter)
anexplicitnullreturn(implyinga@Nullablereturntype)
explicitlycreatedreturnvaluesateachreturnstatement(implyinga@NonNullreturntype).
Inspectingexternalannotations
Theimmediateeffectofexternalannotationscanbeobservedviachangesincompilererrors/warnings.Forfulltransparency,annotatedlibrarysignaturescanbeinspectedusingthe
JavadochoverorJavadocview.
Duetoanimplementationlimitation,thisfeaturecurrentlyonlyworksfortypeannotations(Java8).
Declarationannotationsvstypeannotations
Generally,supportforexternalannotationshasbeendevelopedwithregardtofullysupportingalllocationsofnulltypeannotations(Java8).Thismeans,youmayrefertoanydetail
ofatypeinamethodsignatureandannotate,e.g.,atypeparameter,atypeboundoranarraydimension.Whenusingdeclarationannotations,therelevantsubsetoflocationshares
thesamemechanismsforexternalannotations.
Inonesituationthedesignfortypeannotationsshinesthroughevenwhenusingdeclarationannotations:annotatinganarraytypeisbasedonthenewsyntaxoftypeannotations
(seealsoCompatibility>Syntax).ForillustrationconsiderthefollowingmethodintypeCollection:
Object[]toArray()
EvenwhenaprojectusesJava7orbelow,thereturntypeofthismethodisannotatedbyplacingthecursorbeforethearraybrackets.InvokingAnnotatewillcreateanexternal
annotationthatisinternallyinterpretedasanannotationonthemethod(butstillthemeaningis:describingthereturnofthismethod).
Otherthanthisoneexception,externalannotationscloselymimichowannotationsdirectlywithinasourcefilewouldbehandled,withareducedsetoflocationsfordeclaration
annotations,andthefullsetoflocationsfortypeannotations.
4.10.4.Avoidingresourceleaks
Classesimplementingtheinterfacejava.io.Closeable(sinceJDK1.5)andjava.lang.AutoCloseable(sinceJDK1.7)areconsideredtorepresentexternalresources,which
shouldbeclosedusingmethodclose(),whentheyarenolongerneeded.
TheEclipseJavacompilerisabletoanalyzewhethercodeusingsuchtypesadherestothispolicy.E.g.,thefollowingsnippetrepresentsanobviousresourceleak:
intlen(Filef)throwsIOException{
InputStreamstream=newFileInputStream(f)
returnstream.available()
}
Thecompilerwillflagthiswith"Resourceleak:'stream'isneverclosed".
Basicflowanalysisforresourceleaks
Flowanalysisdetectsthefollowingsituations:
Aresourceisdefinitelynotclosed
Aresourceisnotclosedonallcontrolflows(flaggedas"maynotbeclosed")
Aresourceisnotclosedatamethodexitpoint(returnstatementorwhenanexceptionisraised)(definitelyoronsomecontrolflow)
InaJava7programaresourceisclosedbutthecodecouldstillbeimprovedbyusingatrywithresourcesstatement.
Additionally,flowanalysistriestofollowresourcevaluesthroughvariableassignments.However,ifdifferentresourcesmaybeassignedtothesamevariable(ondifferentcontrol
flowsorinsequence),theanalysiscanbecomelessaccurate.
Notalltheanalysisisenabledbydefault.Pleaseconsultthecompilerpreferencesregardingtheindividualconfigurationoptions.
Hints:Codewillgenerallybeeasiertoanalyze(andeasiertounderstandbyhumanreaders)ifresourcetypevariablesarenotreusedfordifferentpurposes.Ideally,inJava7
programsallresourcesshouldbemanagedwithatrywithresourcesstatement.
Ownership/responsibility
Theabovediagnosticsbasicallyassumethatamethodthatcreatesaninstanceofaresourcetypeisalsoresponsibleforclosingthisresource.However,someresourceswillbe
sharedamongseveralmethods.Heretheanalysismakesthefollowingassumptions:
Ifamethodreturnsaresourcetoitscaller,itisnotresponsibleforclosingnoproblemisreported.
Ifaresourceisstoredinafield,nosinglemethodisconsideredasresponsibleforclosingnoproblemisreported.
Ifamethodobtainsaresourceviaamethodcallratherthanbyanewexpression,itmayormaynotberesponsibleanyproblemsareonlyflaggedaspotentialresourceleaks.
Ifaresourceispassedasanargumentinamethodcallorconstructorcall,thecurrentmethodmayormaynotberesponsibleanyproblemsareonlyflaggedaspotential
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 139/322
12/10/2015 Javadevelopmentuserguide
resourceleaks.
Resourcewrappersandresourcefreecloseables
TheJDKdefinesafewclasseswhichimplementCloseablebutdonotdirectlyrepresentaresourceattheleveloftheoperatingsystem.
java.io.StringReaderisanexampleofacloseablethatdoesn'trequirecallingclose()becausenooperatingsystemresourcesareheldthatwouldrequirecleanup.The
analysisusesanexplicitwhitelisttodetectclassesfromjava.iothatfallinthiscategory.Noresourceleakwarningsareissuedregardingtheseclasses.
Instancesofclasseslikejava.io.BufferedInputStreamarewrappersaroundanotherresource(wherewrapperscanbeappliedatmultiplelevels).Alsotheseobjectsdonot
directlyrepresentanoperatingsystemresource.Ifthewrappedresourceisclosed,thewrapperdoesn'tneedclosing.Conversely,ifawrapperisclosedthiswillincludeclosingof
thewrappedresource.Theanalysishasasecondwhitelistfordetectingwrapperresources,andwillrecognizewhethertheunderlyingactualresourcewillbecloseddirectlyor
indirectlyviathewrapper.Eitheronesufficestosilencewarningsregardingresourceleaks.Thewhitelistcontainsclassesfromjava.io,java.util.zip,java.security,
java.beansandjava.sound.sampled.
Hint:Itisgenerallypreferable/safesttoclosetheoutermostwrapper,notawrappedresource.
4.10.5.Ensuringcompletenessofswitchstatements
Itisgoodpracticetoensurethateachswitchstatementshouldbecompleteinthesensethateachexecutionatruntimewillfindasuitablebranch.Thisisactuallyanontrivialtask
whentakingallofthefollowingintoconsideration:
Differentrulesapplyforswitchesoveranenumvaluevs.intorevenString.
Dependingonthecontext,usingadefaultlabelmayappearundesirableorgoodpracticeorevenmandatory.
Insomecontextsprogramevolutionshouldbesafeguardedbyflagginginconsistentextensionasanerror,whileinothercontextsamoreforgivingstrategyisdesirable.
Additionally,theJLSmandatesaflowanalysisforenumswitchstatementswhichcanleadtounexpectedcompiletimeerrors:
enumColors{RED,GREEN,BLUE}
StringcolorString(Colorc){
switch(c){
caseRED:return"red"
caseGREEN:return"green"
caseBLUE:return"blue"
}
}
Thecompilerwillanswer:
"ThismethodmustreturnaresultoftypeString.Notethataproblemregardingmissing'default:'on'switch'hasbeensuppressed,whichisperhapsrelatedtothis
problem".
Thismessagehasbeendesignedtoalertusersofthedifferentnotionsofcompleteness:theflowanalysismandatedbytheJLSconsiderseachenumswitchstatementwithouta
defaultcaseasincomplete,evenifitlistsall(currentlyknown)enumconstants.Thisconcernsreturnstatementsaswellasdefiniteassignmentoflocalvariablesorblankfinalfields.
However,ifyoufollowallrecommendationsbelow,theaboveerrormessagewillneveroccur.
Pleaseconsultthecompilerpreferencesregardingtheindividualconfigurationoptionsforreportingvariouslevelsofincompleteness.Inthesequelwediscussdifferentdesigngoals
andpoliciesandhowtheycanbecheckedusingtheEclipseJavacompiler.
Onusing"default:"
Optimally,eachswitchstatementshouldhaveameaningfuldefaultbranch,whichhandlesallcasesthatarenotexplicitlylistedusingan"alwaysreasonable"strategy.Obviously,
suchastrategyisdifficultorevenimpossibletofindinmanycases,butifyoucanfindameaningfuldefaultimplementation,that'scertainlythebestsolution.
Recommendation:Bylettingthecompilerwarnyouabouteachswitchstatementlackingadefaultcaseyouareremindedtosearchforagooddefaultimplementationfor
everyswitchstatement.
Ifthecompilerwarnsyouaboutamissingdefaultcase,butthereasonablethingtodobydefaultisjustdonothing,thismightaswellbeworthdocumenting.
Recommendation:If"donothing"isareasonabledefaultstrategyyoushouldaddadefault:labelwhoseactionisonlyacommentexplainingthat(andwhy)doingnothingis
OKinthisswitch.Bydoingsoyoualsotellthecompilerthatyoudidnotsimplyforgetaboutadefaultcase.
Ifdefinitelynoreasonabledefaultimplementationcanbefound,asalastresortyoumaywanttopreventanunexpectedvaluetobetherootcauseforothererrorsfurther
downstream,i.e.,youmaywanttofailearlyatruntime.
Recommendation:Ifneitherareasonabledefaultimplementationcanbefoundnor"donothing"appearstobeagoodstrategy,addadefault:casethatthrowsanexception
and/orlogstheproblem.
Eachswitchstatementshouldbeassignabletooneofthethreeabovecategories.Thismeanslettingthecompilerwarnyouabouteachmissingdefaultcaseisauniversallyvalid
strategy.
Handlingallenumconstants
Whenperformingaswitchoveranenumvalue,itmaybedesirabletoexplicitlycovereachenumconstantbyacorrespondingcasestatement.
Recommendation:Ifyouwanttobewarnedaboutenumswitchstatementsthatlackacasestatementforanyoftheenumconstants,pleaseconsiderenablingtheoption
Signalevenif'default'caseexists.
Ifyoudon'tliketheoptionthatallenumswitchesshouldmentionallenumconstants,butstillwanttogetthewarningaboutmissingcaselabelsforsomeenumswitchstatements,
you'llneedtoselectthestrategyforeachindividualenumswitchstatement.
Recommendation:Iftheabovewarningisdesirableforsomeswitchstatements,considertogloballyenablethewarning,andidentifythoseswitchstatementswhereitisOK
toomitcasesforsomeenumconstants,becausethosearesuitablyhandledbythedefaultcase.Fortheseswitchstatementsusethe'//$CASESOMITTED$'tagcomment
todocumentyourdecision:
StringcolorString2(Colorc){
switch(c){
caseRED:return"red"
caseGREEN:return"green"
//$CASESOMITTED$
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 140/322
12/10/2015 Javadevelopmentuserguide
default:
return"unknowncolor"
}
}
Hint:Ifthecompilerreportssomethinglike"TheenumconstantBLUEshouldhaveacorrespondingcaselabelinthisenumswitchonColor"aquickfixwillbeofferedforinserting
thetagcomment.
Summary
Theaboveconsiderationshaveshownthatyougetmosthelpfromthecompilerifyouenablealloptionalwarningsregardingincompleteswitchstatements,anduseempty
documenteddefaultcasesplus//$CASESOMITTED$tagcommentstomarkthoseswitchstatementswhereincompletenessisOKbydesign.Ifyoufollowtheserecommendations,
youwillgetallrelevantwarnings(orerrorsifyoulike)whenbranchesareaccidentallyomitted,includingthesituationoflateadditionofoneormoreenumconstants.Allexceptions
fromthismaximumcompletenesswillbedocumentedinthecodeandnolongerflaggedwithawarning.
Stillthecompilercannotpreventtheuseofinconsistentclassversionsatruntime,soaclassmaybecompiledagainstanoldversionofanenumtype,butintherunningapplication
theenumtypemayhavemoreenumconstants.Fortheseandsimilarsituationsanappropriate"catchall"defaultimplementationscanraiseruntimeexceptionstoalertofthis
inconsistencyandpreventtheerrorfrompropagatingfurtherintotheapplication.
Asanaddedvalueofthestrictcompilersettingsrecommendedabove,thedubiouserrormessageaboutamissingreturnstatementshownabove(orsimilarmessagesabout
uninitializedvariables)willnolongeroccur.
4.11.UsingtheFormatterApplication
TheJDThasacommandlineEclipseapplicationthatallowsuserstoformatJavasourcecodeeitherwiththeEclipsedefaultcodeformatteroptionsorwithcustomoptions.
Runningtheformatterapplication
CodeFormatter
4.11.1.RunningtheFormatterApplication
Runningtheformatterapplicationisassimpleasrunningtheorg.eclipse.jdt.core.JavaCodeFormatterapplicationfromthecommandline:
eclipsevm<pathtovirtualmachine>applicationorg.eclipse.jdt.core.JavaCodeFormatter[OPTIONS]<files>
WheninvokedonMacOS,thepathstopointtotheconfigurationfileorthesourcefilescanberelative,buttheywillbecomputedfromthelocationoftheeclipse.inifile.Thisisa
limitationoftheEclipselauncheronMacOS.Onallotherplatforms,therelativepathsarecomputedrelativetothecurrentuserdirectory.
Javasourcefilesand/ordirectoriestoformat.Onlyfilesendingwith.java
<files>
willbeformattedinthegivendirectory.
OPTIONS Description
config<file> Usetheformattingstylefromthespecifiedpropertiesfile.Referto
Generatingaconfigfilefortheformatterapplicationfordetails.
help Displaythehelpmessage.
quiet Onlyprinterrormessages.
verbose Beverboseabouttheformattingjob.
Codeformatter
4.11.2.GeneratingaConfigFilefortheFormatterApplication
GeneratingaconfigfilefortheformatterapplicationinvolvesmodifyingthecodeformattersettingsforaJavaprojectandcopyingorg.eclipse.jdt.core.prefsoutofthe.settings
directoryforthatproject.
1. SelectaJavaproject,openthepopupmenuandchooseProperties.
2. SelecttheJavaCodeStyle>FormatterpageandcheckEnableprojectspecificsettings.
3. Selectoreditaprofileasexplainedabove.
4. ClickOKwhenyouaredone.
5. Useeitherafilemanagerorthecommandlinetocopyworkspace/YourJavaProject/.settings/org.eclipse.jdt.core.prefstoanewlocation.
6. Ifthefilesyouwanttoformatareusing1.5constructs,youmustaddthefollowinglinesinsidethepreferencefileyoujustcreated:
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.source=1.5
Codeformatter
5.1.1.BreakpointEnableCondition
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 141/322
12/10/2015 Javadevelopmentuserguide
SelecttheConditionaloptiontoenabletheabilitytoprovideacustomconditionforthebreakpoint.
Eachbreakpointcanhaveauniqueconditionthatdetermineswhenthebreakpointwillbehit.
Aconditionforabreakpointcanbeanylogicalexpressionthatevaluatestoeithertrueorfalse.Theexpressionisevaluatedinthescopeofthebreakpointlocation,meaningyou
cannotmakereferencetoaclass,etc.,outsidethescopeofthebreakpointlocationwhencomposingyourexpression.
Considerthefollowingexample:
publicclassPerson{
Stringname=""
intage=0
publicPerson(Stringname,intage){
this.name=name
this.age=age //breakpointhere
}
}
Ifwetaketheaboveexample,placeabreakpointwhereindicatedandgotothebreakpointpropertieswecanaddourcondition.Inthiscasewearelimitedonlytothemembersofthe
classthebreakpointiscontainedinandthoseprovidedbyObject.
Forexampleavalidconditioncouldbe:
age==56
meaningthebreakpointwouldonlysuspendwhenagewasequalto56.
ConditionscanbeaddedtobreakpointsintheBreakpointsViewdetailpaneorwiththeBreakpointsProperties...shownbelow.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
EnabledOption
HitCount
SuspendPolicy
MethodEntry
MethodExit
5.1.2.BreakpointEnabled
SelecttheEnabledoptiontoenableordisableabreakpoint.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,byrightclickingabreakpoint,orbyselectingthebreakpointoritsgroupingin
theBreakpointsView.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 142/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
HitCount
SuspendPolicy
5.1.3.ExceptionBreakpointCaughtException
SelecttheCaughtlocationsoptiontosuspendexecutionwhenanexceptionofthesametypeasthebreakpointisthrowninacaughtlocation.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickinganexceptionbreakpoint.
Breakpoints
Catchingexceptions
CreatingExceptionBreakpointFilters
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
AddJavaexceptionbreakpoint
EnabledOption
HitCount
SuspendPolicy
5.1.4.ExceptionBreakpointSuspendonSubclassofthisException
SelecttheSubclassesofthisexceptionoptiontosuspendexecutionwhensubclassesoftheexceptiontypeareencountered.
Forexample,ifanexceptionbreakpointforRuntimeExceptionisconfiguredtosuspendonsubclasses,itwillalsobetriggeredbyaNullPointerException.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 143/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
AddJavaexceptionbreakpoint
EnabledOption
HitCount
SuspendPolicy
CaughtOption
UncaughtOption
5.1.5.ExceptionBreakpointUncaughtException
SelecttheUncaughtlocationsoptiontosuspendexecutionwhenanexceptionofthesametypeasthebreakpointisthrowninanuncaughtlocation.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickinganexceptionbreakpoint.
Breakpoints
Catchingexceptions
CreatingExceptionBreakpointFilters
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
AddJavaexceptionbreakpoint
5.1.6.BreakpointHitCount
SelecttheHitCountoptiontodefineahitcountfortheselectedbreakpoint.
TheHitCountoptionisusedtodeterminewhenyourprogramshouldsuspendonthatbreakpoint.
IfabreakpointhasahitcountofN,executionwillsuspendwhenthebreakpointisencounteredfortheNthtime.Afterbeinghit,thebreakpointisdisableduntileitheritisreenabled
oritshitcountischanged.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 144/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
EnabledOption
SuspendPolicy
5.1.7.BreakpointMethodEntry
SelecttheEntryoptiontosuspendexecutionwhenthemethodassociatedwiththebreakpointisentered.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingamethodbreakpoint.
Breakpoints
Settingmethodbreakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
EnabledOption
HitCount
SuspendPolicy
MethodExit
BreakpointConditions
5.1.8.BreakpointMethodExit
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 145/322
12/10/2015 Javadevelopmentuserguide
SelecttheExitoptiontosuspendexecutionwhenthemethodassociatedwiththebreakpointisexited.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingamethodbreakpoint.
Breakpoints
Settingmethodbreakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
EnabledOption
HitCount
SuspendPolicy
MethodExit
BreakpointConditions
5.1.9.BreakpointSuspendPolicy
Abreapoint'ssuspendpolicydetermineswhatshouldbesuspendedwhenabreakpointishit.
TherearetwooptionsforJavabreakpoints:
Suspendthreadsuspendsonlythethreadthatencounteredthebreakpoint
SuspendVMsuspendstheentireVMwhenthebreakpointisencountered
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.
Youcanalsochangethedefaultsettingforthesuspendpolicyforallnewlycreatedbreakpoints.
Todothisgotothe Java>Debugpreferencepageandchangeitthere.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 146/322
12/10/2015 Javadevelopmentuserguide
EnabledOption
HitCount
5.1.10.WatchpointFieldModification
SelecttheModificationoptiontosuspendexecutionwhentheassociatedfieldismodified(written).
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingawatchpoint.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
OpeningtheBreakpointPropertiesDialog
WatchpointModificationContextAction
EnabledOption
HitCount
SuspendPolicy
5.1.11.WatchpointFieldAccess
SelecttheAccessoptiontosuspendexecutionwhentheassociatedfieldisaccessed(read).
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingawatchpoint.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
OpeningtheBreakpointPropertiesDialog
WatchpointAccessContextAction
EnabledOption
HitCount
SuspendPolicy
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 147/322
12/10/2015 Javadevelopmentuserguide
5.2.JDTActions
JDTactionsareavailablefrom
Menubar
Toolbar
Contextmenusinviews
Javadevelopmenttools(JDT)
FrequentlyaskedquestionsonJDT
JDTglossary
Filemenuactions
Editmenuactions
Sourcemenuactions
Refactormenuactions
Navigatemenuactions
Searchmenuactions
Projectmenuactions
Runmenuactions
Javatoolbaractions
Runanddebugtoolbaractions
Javaeditoractions
5.2.1.Fileactions
Filemenucommands:
Keyboard
Name Function
Shortcut
Alt+Shift
New CreateaJavaelementoranewresource.ConfigurewhichelementsareshowninthesubmenuinWindow>CustomizePerspective.InaJava +N
perspective,bydefaultactionforcreatingaproject,package,class,interface,enum,annotation,sourcefolder,Javaworkingset,JUnittest,fileand
folderareavailable.
OpenFile Opensafilefromthefilesysteminaneditor.
Ctrl+
CloseAll Closealleditors.Ifeditorscontainsunsaveddata,asaverequestdialogwillbeshown.
Shift+W
SaveAs Savethecontentofthecurrenteditorunderanewname.
Ctrl+
SaveAll Savethecontentofalleditorswithunsavedchanges.Disabledifnoeditorcontainsunsavedchanges.
Shift+S
Revert Revertthecontentofthecurrenteditorbacktothecontentofthesavedfile.Disablediftheeditordoesnotcontainunsavedchanges.
Move Movearesource.DisabledonJavaElements.TomoveJavaelementsuseRefactor>Move(withupdatingallreferencestothefile)orEdit>Cut/
Paste(noupdatingofreferences).
Rename Renamesaresource.DisabledonJavaElements.TorenameJavaelementsuseRefactor>Rename(withupdatingallreferencestothefile).
Refresh Refreshesthecontentoftheselectedelementwiththelocalfilesystem.Whenlaunchedfromnospecificselection,thiscommandrefreshesallprojects. F5
Convert
Line
Convertthelinedelimitersofallthetextfilesintheselectiontotheselecteddelimiterkind.
Delimiters
To
Print Printsthecontentofthecurrenteditor.Enabledwhenaneditorhasthefocus. Ctrl+P
Switch
Switchtoanotherworkspace.
Workspace
Restart Restartstheapplication.
Import Openstheimportwizarddialog.JDTdoesnotcontributeanyimportwizards.
Export Openstheexportwizarddialog.JDTcontributestheJARfileexportwizardandtheJavadocgenerationwizard.
Properties Opensthepropertypagesoftheselectelements.OpenedonJavaprojectstheJavaBuildPathpageandtheJavadocLocationpageareavailable.For Alt+
JARarchives,configuretheJAR'sSourceAttachmentandJavadocLocationhere. Enter
Exit ExitEclipse
Javadevelopmenttools(JDT)
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 148/322
12/10/2015 Javadevelopmentuserguide
CreatingJARfiles
NewJavaprojectwizard
NewJavapackagewizard
NewJavaclasswizard
NewJavaenumwizard
NewJavainterfacewizard
NewJavaannotationwizard
JARfileexporter
Javadocgeneration
Javadoclocationproperties
Javabuildpathproperties
Sourceattachmentproperties
5.2.2.Editactions
EditmenucommandsshownwhenaJavaeditorisvisible:
Keyboard
Name Function
Shortcut
Ctrl+Z
Undo Revertthelastchangeintheeditor
Cut Copiesthecurrentlyselectedtextorelementtotheclipboardandremovestheelement.Onelements,theremoveisnotperformedbeforethe
Ctrl+X
clipboardispasted.
CopyQualified Copiesthefullyqualifiednameofthecurrentlyselectedelementtotheclipboard
Name
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 149/322
12/10/2015 Javadevelopmentuserguide
Javaeditor
Javadevelopmenttools(JDT)
Javaeditor
Javaeditorpreferences
Javaoutline
Viewsandeditors
5.2.3.SourceActions
Sourcemenucommands:
Keyboard
Name Function
Shortcut
Ctrl+/
ToggleComment Commentoruncommentalllinescontainingthecurrentselection.
Ctrl+
AddBlock Addsablockcommentaroundalllinescontainingthecurrentselection. Shift+/
Comment
ShiftRight Incrementsthelevelofindentationofthecurrentlyselectlines.Onlyactivatedwhentheselectioncoversmultiplelinesorasinglewholeline.
ShiftLeft Decrementsthelevelofindentationofthecurrentlyselectlines.Onlyactivatedwhentheselectioncoversmultiplelinesorasinglewholeline.
Ctrl+
Format Usesthecodeformattertoformatthecurrenttextselection.TheformattingoptionsareconfiguredontheCodeFormatterpreferencepage.
Shift+F
FormatElement UsesthecodeformattertoformattheJavaelementcomprisingthecurrenttextselection.TheFormatElementactionworksonmethodandtype
level.TheformattingoptionsareconfiguredontheCodeFormatterpreferencepage.
SortMembers SortsthemembersofatypeaccordingtothesortingorderspecifiedintheMemberSortOrderpreferencepage
CleanUp PerformsvariouschangesinordertocleanupyourcodeaccordingtothesettingsspecifiedintheCleanUppreferencepage
Override/Implement OpenstheOverrideMethoddialogthatallowsyoutooverrideorimplementamethodinthecurrenttype.Availableontypesoronatextselection
Methods insideatype.
GenerateGetter OpenstheGenerateGettersandSettersdialogthatallowsyoutocreateGettersandSettersforfieldsinthecurrenttype.Availableonfieldsand
andSetter typesoronatextselectioninsideatype.
GenerateDelegate OpenstheGenerateDelegateMethodsdialogthatallowsyoutocreatemethoddelegatesforfieldsinthecurrenttype.Availableonfieldsand
Methods typeswithfields.
Generate OpenstheGenerateHashCodeandEqualsdialogthatallowsyoutostartandcontrolthegenerationofhashCodeandequalsmethodsinthe
hashCode()and currenttype.
equals()
GeneratetoString() OpenstheGeneratetoString()dialogthatallowsyoutostartandcontrolthegenerationofatoString()methodinthecurrenttype.
Generate
Constructorusing Addsconstructorswhichinitializefieldsforthecurrentlyselectedtypes.Availableontypes,fieldsoronatextselectioninsideatype.
Fields
AddConstructor
Addsconstructorsasdefinedinthesuperclassforthecurrentlyselectedtypes.Availableontypesoronatextselectioninsideatype.
fromSuperclass
Surroundtheselectedstatementswithacodetemplate.CreateyourowntemplatesontheTemplatepreferencepage.Further,youcan Alt+Shift
SurroundWith
useExpandSelectiontofromtheEditmenutogetavalidselectionrange. +Z
ExternalizeStrings OpenstheExternalizestringswizard.Thiswizardsallowsyoutoreplaceallstringsinthecodebystatementsaccessingapropertyfile.
FindBroken Searchesforbrokenexternalizedstringsinaselectedpropertyfile,package,projectorsetofprojects.
Externalized
Strings
Javaeditor
Stringexternalization
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 150/322
12/10/2015 Javadevelopmentuserguide
Javadevelopmenttools(JDT)
Externalizingstrings
Javaeditor
Javaeditorpreferences
Javaoutline
Viewsandeditors
5.2.4.RefactorActions
Refactormenucommands:
Name Description
Renamestheselectedelementand(ifenabled)correctsallreferencestotheelements(alsoinotherfiles).
Rename
Available: Methods,methodparameters,fields,localvariables,types,typeparameters,enumconstants,compilationunits,packages,sourcefolders,
projectsandonatextselectionresolvingtooneoftheseelementtypes
Shortcut: Alt+Shift+R
Options: Renamingatypedoesallowtorenamesimilarlynamedvariablesandmethods.Enable'Updatesimilarlynamedvariablesandmethods'inthe
RenameTypedialog.Select'Configure...'toconfigurethestrategyformatchingtypenames.
Renamingapackagedoesallowtorenameitssubpackages.Enable'Renamesubpackages'intheRenamePackagedialog.
Enable'Keeporiginalmethodasdelegatetochangedmethod'tokeeptheoriginalmethod.Optionallyyoucandeprecatetheoldmethod.
Movestheselectedelementsand(ifenabled)correctsallreferencestotheelements(alsoinotherfiles).
Move
Available: Instancemethod(whichcanbemovedtoacomponent),oneormorestaticmethods,staticfields,types,compilationunits,packages,source
foldersandprojectsandonatextselectionresolvingtooneoftheseelementtypes
Shortcut: Alt+Shift+V
Options: YoucanuseDrag&DropinthePackageExplorertostartthisrefactoring.
ChangeMethod Changesparameternames,parametertypes,parameterorderandupdatesallreferencestothecorrespondingmethod.Additionally,parametersandthrown
Signature exceptionscanberemovedoraddedandmethodreturntypeandmethodvisibilitycanbechanged.
Available: Methodsorontextselectionresolvingtoamethod
Shortcut: Alt+Shift+C
Options: Enable'Keeporiginalmethodasdelegatetochangedmethod'intheChangeMethodSignaturedialogtokeeptheoriginalmethod.
ExtractMethod Createsanewmethodcontainingthestatementsorexpressioncurrentlyselectedandreplacestheselectionwithareferencetothenewmethod.This
featureisusefulforcleaninguplengthy,cluttered,oroverlycomplicatedmethods.
Available: YoucanuseExpandSelectiontofromtheEditmenutogetavalidselectionrange.
Thisrefactoringisalsoavailableasquickassistonstatementsandexpressionsselectedintheeditor.
Shortcut: Alt+Shift+M
ExtractLocal Createsanewvariableassignedtotheexpressioncurrentlyselectedandreplacestheselectionwithareferencetothenewvariable.
Variable Available: Textselectionsthatresolvetolocalvariables.YoucanuseExpandSelectiontofromtheEditmenutogetavalidselectionrange.
Thisrefactoringisalsoavailableasquickassistonexpressionsselectedintheeditor.
Shortcut: Alt+Shift+L
ExtractConstant Createsastaticfinalfieldfromtheselectedexpressionandsubstitutesafieldreference,andoptionallyrewritesotherplaceswherethesameexpression
occurs.
Available: Constantexpressionsortextselectionswhichresolvetoconstantexpressions
Thisrefactoringisalsoavailableasquickassistonexpressionsselectedintheeditor.
Inline Inlinelocalvariables,methodsorconstants.
Available: Methods,staticfinalfieldsandtextselectionsthatresolvetomethods,staticfinalfieldsorlocalvariables
Thisrefactoringisalsoavailableasquickassistonlocalvariablesselectedintheeditor.
Shortcut: Alt+Shift+I
ConvertAnonymous Convertsananonymousinnerclasstoamemberclass.
ClasstoNested Available: Anonymousinnerclasses
MoveTypetoNew CreatesanewJavacompilationunitfortheselectedmembertypeortheselectedsecondarytype,updatingallreferencesasneeded.Fornonstatic
File membertypes,afieldisaddedtoallowaccesstotheformerenclosinginstance,ifnecessary.
Available: Membertypes,secondarytypes,ortextresolvingtoamembertypeorasecondarytype.
ConvertLocal Turnalocalvariableintoafield.Ifthevariableisinitializedoncreation,thentheoperationmovestheinitializationtothenewfield'sdeclarationortothe
VariabletoField class'sconstructors.
Available: Textselectionsthatresolvetolocalvariables.
Thisrefactoringisalsoavailableasquickassistonlocalvariablesselectedintheeditor.
ExtractSuperclass Extractsacommonsuperclassfromasetofsiblingtypes.Theselectedsiblingtypesbecomedirectsubclassesoftheextractedsuperclassafterapplying
therefactoring.
Available: Types
Options: Enable'Usetheextractedclasswherepossible'tousethenewlycreatedclasswhereverpossible.SeeUseSupertypeWherePossible.
ExtractInterface Createsanewinterfacewithasetofmethodsandmakestheselectedclassimplementtheinterface.
Available: Types
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 151/322
12/10/2015 Javadevelopmentuserguide
Options: Enable'Usetheextractedinterfacetypewherepossible'tousethenewlycreatedinterfacewhereverpossible.SeeUseSupertypeWhere
Possible.
UseSupertype Replacesoccurrencesofatypewithoneofitssupertypesafteridentifyingallplaceswherethisreplacementispossible.
WherePossible Available: Types
PushDown Movesasetofmethodsandfieldsfromaclasstoitssubclasses.
Available: Oneormoremethodsandfieldsdeclaredinthesametypeoronatextselectioninsideafieldormethod
PullUp Movesafieldormethodtoasuperclassofitsdeclaringclassor(inthecaseofmethods)declaresthemethodasabstractinthesuperclass.
Available: Oneormoremethods,fieldsandmembertypesdeclaredinthesametypeoronatextselectioninsideafield,methodormembertype
ExtractClass Replacesasetoffieldswithnewcontainerobject.Allreferencestothefieldsareupdatedtoaccessthenewcontainerobject.
Available: Thesetoffieldsoratypecontainingfields
Options: Enable'CreateGetterandSetters'toaddaccessormethodstothenewtype
IntroduceParameter Replacesasetofparameterswithanewclass,andupdatesallcallersofthemethodtopassaninstanceofthenewclassasthevaluetotheintroduce
Object parameter.
Available: Methodsorontextselectionresolvingtoamethod
Options: Enable'Keeporiginalmethodasdelegatetochangedmethod'intheIntroduceParameterObjectdialogtokeeptheoriginalmethod.
IntroduceIndirection Createsastaticindirectionmethoddelegatingtotheselectedmethod.
Available: Methodsorontextselectionresolvingtoamethod
Options: Enable'Redirectallmethodinvocations'toreplaceallcallstotheoriginalmethodbycallstotheindirectionmethod.
IntroduceFactory Createsanewfactorymethod,whichwillcallaselectedconstructorandreturnthecreatedobject.Allreferencestotheconstructorwillbereplacedbycalls
tothenewfactorymethod.
Available: Constructordeclarations
IntroduceParameter Replacesanexpressionwithareferencetoanewmethodparameter,andupdatesallcallersofthemethodtopasstheexpressionasthevalueofthat
parameter.
Available: Textselectionsthatresolvetoexpressions
EncapsulateField Replacesallreferencestoafieldwithgetterandsettermethods.
Available: Fieldoratextselectionresolvingtoafield.
Thisrefactoringisalsoavailableasquickassistonfielddeclarationsandreferencesselectedintheeditor.
GeneralizeDeclared Allowstheusertochooseasupertypeofthereference'scurrenttype.Ifthereferencecanbesafelychangedtothenewtype,itis.
Type Available: Typereferencesanddeclarationsoffields,localvariables,andparameterswithreferencetypes
InferGenericType Replacesrawtypeoccurrencesofgenerictypesbyparameterizedtypesafteridentifyingallplaceswherethisreplacementispossible.
Arguments Available: Projects,packages,andtypes
Options: 'Assumeclone()returnsaninstanceofthereceivertype'.Wellbehavedclassesgenerallyrespectthisrule,butifyouknowthatyourcode
violatesit,uncheckthebox.
'Leaveunconstrainedtypeargumentsraw(ratherthaninferring<?>)'.Iftherearenoconstraintsontheelementsofe.g.ArrayLista,uncheck
thisboxwillcauseEclipsetostillprovideawildcardparameter,replacingthereferencewithArrayList<?>.
MigrateJARFile MigratesaJARFileonthebuildpathofaprojectinyourworkspacetoanewerversion,possiblyusingrefactoringinformationstoredinthenewJARFileto
avoidbreakingchanges.
Available: JARFilesonbuildpath
CreateScript Createsascriptoftherefactoringsthathavebeenappliedintheworkspace.Refactoringscriptscaneitherbesavedtoafileorcopiedtotheclipboard.See
ApplyScript.
Available: Always
ApplyScript Appliesarefactoringscripttoprojectsinyourworkspace.Refactoringscriptscaneitherbeloadedfromafileorfromtheclipboard.SeeCreateScript.
Available: Always
History Browsestheworkspacerefactoringhistoryandofferstheoptiontodeleterefactoringsfromtherefactoringhistory.
Available: Always
RefactoringcommandsarealsoavailablefromthecontextmenusinmanyviewsandtheJavaeditor.
Refactoringsupport
Refactoringdialogs
Javapreferences
5.2.5.NavigateActions
Navigatemenucommands:
Keyboard
Name Function
Shortcut
GoInto Setstheviewinputtothecurrentlyselectedelement.SupportedbythePackageExplorerview.
GoTo Back:Setstheviewinputtotheinputbackinhistory:Onlyenabledwhenahistoryexists(GoIntowasused)
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 152/322
12/10/2015 Javadevelopmentuserguide
Forward:Setstheviewinputtotheinputforwardinhistory:Onlyenabledwhenahistoryexists(GoInto,GoTo>Backwereused)
UpOneLevel:Setstheinputofthecurrentviewtoitsinput'sparentelement
Type:Browseforatypeandrevealitinthecurrentview.SupportedbythePackageExplorerview
Package:Browseforapackageandrevealitinthecurrentview.SupportedbythePackageExplorerview
Resource:Browseforaresourceandrevealitinthecurrentview.
Open Triestoresolvetheelementreferencedatthecurrentcodeselectionandopensthefiledeclaringthereference.
F3
Declaration
OpenType TriestoresolvetheelementreferencedatthecurrentcodeselectionandopenstheelementintheTypeHierarchyview.Invokedonelements,
F4
Hierarchy opensthetypehierarchyoftheelement.SupportedintheJavaeditorandviewsshowingJavaelements.
OpenCall TriestoresolvethemethodreferencedatthecurrentcodeselectionandopenstheelementintheCallHierarchyview.
Ctrl+Alt+H
Hierarchy
Open Openstheimplementationofthecurrentlyselectedmethodifthere'sonlyoneimplementor,elseopenstheQuickTypeHierarchyonthatmethod.
Implementation
OpenSuper Openaneditorforthesuperimplementationofthecurrentlyselectedmethodormethodsurroundingthecurrentcursorposition.Noeditorisopened
Implementation ifnomethodisselectedorthemethodhasnosuperimplementation.
OpenstheJavadocdocumentationofthecurrentlyselectedelementortextselection.ThelocationoftheJavadocofaJARoraprojectisspecified
OpenAttached
intheJavadoclocationpropertypageonprojectsorJARs.NotethatthisattachedJavadocdocumentationmaynotbeuptodatewiththeJavadoc Shift+F2
Javadoc
specifiedinthecurrentcode.YoucancreateJavadocdocumentationforsourcefilesinaJavaprojectusingtheJavadocexportwizard.
TriestoopenthematchingJavaelementintheeditoriftheclipboardcontainsasingleline.OtherwiseitopensthecontentsintheJavaStackTrace
Console.Examples:
java.lang.String
String
String#getBytes
Openfrom String.getBytes
Clipboard
java.lang.String.getBytes(String)
String.java:123
atjava.lang.String.matches(String.java:1550)
java.lang.String.valueOf(char)line:1456
currentTimeMillis()
Open OpenstheOpenResourcedialogtoopenanyresourceinyourworkspace.
Ctrl+Shift+R
Resource
ShowsthecurrentlyselectedelementinthebreadcrubbaroftheJavaeditor.
ShowIn
Ctrl+Shift+B
Breadcrumb
LastEdit
Revealsthelocationwherethelasteditoccurred. Ctrl+Q
Location
GotoLine Opensadialogwhichallowsenteringthelinenumbertowhichtheeditorshouldjumpto.Editoronly. Ctrl+L
Back Revealsthepreviouseditorlocationinthelocationhistory. Alt+Left
Forward Revealsthenexteditorlocationinthelocationhistory. Alt+Right
Javaviews
Javadevelopmenttools(JDT)
Openinganeditorforaselectedelement
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 153/322
12/10/2015 Javadevelopmentuserguide
Showinganelementinthepackageexplorer
Openingatypeinthepackageexplorer
Openinganeditoronatype
Openingapackage
PackageExplorerview
TypeHierarchyview
Javadoclocationproperties
Javadocexportwizard
5.2.6.SearchActions
Searchmenucommands:
Name Function
Search... Opensthesearchdialog(Ctrl+H)
File... OpensthesearchdialogontheFilesearchpage
Java... OpensthesearchdialogontheJavasearchpage
Text Searchesfortheselectedtextinthechosenscope:
Workspace(Ctrl+Alt+G)
Project
Hierarchy
WorkingSet
References FindsallreferencestotheselectedJavaelementinthechosenscope:
Workspace(Ctrl+Shift+G):
Project
Hierarchy
WorkingSet
Declarations FindsalldeclarationsoftheselectedJavaelementinthechosenscope:
Workspace(Ctrl+G)
Project
Hierarchy
WorkingSet
Note:Astrictdeclarationsearchwouldonlyeverreturnasingledeclaration.Sincethat'snotinteresting,declarationsearchesarerelaxedasfollows:
Methoddeclarations:Hierarchysearchfindsoverridingandoverriddenmethodsinthehierarchy.Othersearchesfindmethodswiththesamenameand
signature,butignoringdeclaringtypeandreturntype.
Fielddeclarations:Ignorethedeclaringtypeandthefield'stype.
Implementors Findsallimplementorsoftheselectedinterfaceinthechosenscope:
Workspace
Project
WorkingSet
ReadAccess
Findsallreadaccessestotheselectedfieldinthechosenscope:
Workspace
Project
Hierarchy
WorkingSet
WriteAccess
Findsallwriteaccessestotheselectedfieldinthechosenscope:
Workspace
Project
Hierarchy
WorkingSet
Occurrences FindsalloccurrencesoftheselectedJavaelementinitsfile(Ctrl+Shift+U)
inFile
Identifier:Occurrencesofallidentifiersresolvingtotheselectedelement
ImplementingMethods:Allmethodsimplementedbytheselectedsuperinterfacedeclaration
ThrowingExceptions:Allstatementsthatpossiblethrowtheselecteddeclaredexception
MethodExits:Allstatementsthatcanexitthemethodoftheselectedreturntype
Break/ContinueTarget:Thetargetsoftheselectedbreakandcontinuestatement
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 154/322
12/10/2015 Javadevelopmentuserguide
Referring FindsallJUnitteststhatrefertothecurrentlyselectedtype
Tests
Searchscopessubmenu:
Customscopescanbeconfiguredusingtheworkingsetdialog.ExistingworkingsetsareshownintheSearchscopesubmenusafterthey'vebeenusedinasearch.
AJavasearchcanalsobeconductedviathecontextmenuofallJavaviews.ThesearchcontextmenuisalsoavailableintheJavaeditor.Thesearchisonlyperformedifthe
currentlyselectedtextcanberesolvedtoaJavaelement.
ThetypeoftheselectedJavaelementdefineswhichsearchcontextmenusareavailable.TheJavaeditordoesnotconstrainthelistofavailableJavasearchesbasedonthe
selection.
Javasearch
Javasearchtab
5.2.7.ProjectActions
Projectmenucommands:
Keyboard
Name Function
Shortcut
OpenProject Showsadialogthatcanbeusedtoselectaclosedprojectandopenit
CloseProject Closesthecurrentlyselectedprojects
BuildAll Buildsallprojectsintheworkspace.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethelasttimeofbuildand
Ctrl+B
minimizesthenumberofchangedfiles.
BuildProject Buildsthecurrentlyselectedproject.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethelasttimeofbuildand
minimizesthenumberofchangedfiles.
Build Buildstheprojectscontainedinthecurrentlyselectedworkingset.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessince
WorkingSet thelasttimeofbuildandminimizesthenumberofchangedfiles.
Clean... Showsadialogwheretheprojectstobecleanedcanbeselected.
Build Ifselected,allmodifiedfilesareautomaticallyrebuiltifsaved.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethe
Automatically lasttimeofbuildandminimizesthenumberofchangedfiles.
Generate
OpenstheGenerateJavadocwizardonthecurrentlyselectedproject.
Javadoc...
Properties Opensthepropertypagesonthecurrentlyselectedproject.
Javaprojects
Javabuilder
5.2.8.RunMenuActions
TheRunMenu,foundonthemainmenuoftheEclipseworkbenchcontainsalloftheactionsrequiredrun,debug,stepthroughcodeandworkwithbreakpoints.Differentpartsofthe
menuarevisibleatdifferenttimes,aseachperspectivecanbecustomizedtoshowonlyspecificcapabilities.
TheRunMenucommands.
RunMenuCommands
AddJavaException OpenstheAddJavaExceptiondialogtoselecttheexceptionbreakpointtypetocreate
Breakpoint
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 155/322
12/10/2015 Javadevelopmentuserguide
AddClassLoadBreakpoint OpenstheSelectTypedialogtoselecttheJavatypetoaddaclassloadbreakpointto
AllInstances... DisplaysalloftheinstancesoftheselectedtypeinthecurrentVMinapopup(onlyavailablewithaJava1.6
Ctrl+Shift+N
VM)
AllReferences... DisplaysallofthereferencesoftheselectedtypeinthecurrentVMinapopup(onlyavailablewithaJava1.6
VM)
DebugAs Presentsasubmenuofregistereddebuglaunchshortcuts.Launchshortcutsprovidesupportforworkbenchor
activeeditorselectionsensitivelaunching.
DebugHistory Presentsasubmenuoftherecenthistoryoflaunchconfigurationslaunchedindebugmode
OpenDebugDialog... Thiscommandopensthelaunchconfigurationdialogtomanagedebugmodelaunchconfigurations.
OpenRunDialog... Opensthelaunchconfigurationdialogtomanagerunmodelaunchconfigurations.
RemoveAllBreakpoints Removesallofthebreakpointsfromthecurrentworkspace
Resume Resumesasuspendedthread. F8
RunAs Presentsasubmenuofregisteredrunlaunchshortcuts.Launchshortcutsprovidesupportforworkbenchor
activeeditorselectionsensitivelaunching.
RunHistory Presentsasubmenuoftherecenthistoryoflaunchconfigurationslaunchedinrunmode
StepInto Stepsintothecurrentstatement. F5
StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyou
areattheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. F6
Thecursorjumpstothedeclarationofthemethodandselectsthisline.
StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod. F7
Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.
ToggleLineBreakpoint Togglesalinebreakpointonthecurrentexecutablelineofcode
ToggleMethodBreakpoint Togglesamethodbreakpointonthecurrentlyselectedmethoddeclaration
ToggleWatchpoint Togglesawatchpointonthecurrentlyselectedfield
Watch Usedtocreateawatchitem.AwatchitemisanexpressionintheExpressionsviewwhosevalueisupdatedas
youdebug.
Debugger
Javadevelopmenttools(JDT)
LocalDebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 156/322
12/10/2015 Javadevelopmentuserguide
RemoteDebugging
RunningandDebugging
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
AddingLinebreakpoints
Settingmethodbreakpoints
Catchingexceptions
DebugPreferences
RunandDebugtoolbaractions
5.2.9.JavaToolbarActions
JavaActions
Toolbar
Command Description
Button
CreateaJava ThiscommandhelpsyoucreateanewJavaproject.
Project
SeenewJavaprojectwizard
CreateaJava ThiscommandhelpsyoucreateanewJavapackage.
Package
SeenewJavapackagewizard
CreateaJava ThiscommandhelpsyoucreateanewJavaclass.
Class
SeenewJavaclasswizard
CreateaJava ThiscommandhelpsyoucreateanewJavaenum.
enum
SeenewJavaenumwizard
CreateaJava ThiscommandhelpsyoucreateanewJavainterface.
Interface
SeenewJavainterfacewizard
CreateaJava ThiscommandhelpsyoucreateanewJavaannotation.
annotation
SeenewJavaannotationwizard
CreateaJUnit ThiscommandhelpsyoucreateanewJUnittestcase.
testcase
OpenType ThiscommandallowsyoutobrowsetheworkspaceforatypetoopeninthedefineddefaultJavaeditor.Youcanoptionallychoosetodisplaythe
typesimultaneouslyintheTypeHierarchyview.SeeOpenTypedialog.
Javadevelopmenttools(JDT)
Openinganeditoronatype
NewJavaprojectwizard
NewJavapackagewizard
NewJavaclasswizard
NewJavaenumwizard
NewJavainterfacewizard
NewJavaannotationwizard
NewJavascrapbookpagewizard
Viewsandeditors
5.2.10.RunandDebugtoolbaractions
RunandDebugtoolbaractions
Toolbar
Command Description
Button
Run Thiscommandrelaunchesthemostrecentlylaunchedapplication,orlaunchestheselectedresourceoractiveeditordependingonthelaunchoperation
preferencesettingsfoundontheRun/Debug>Launchingpreferencepage
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 157/322
12/10/2015 Javadevelopmentuserguide
Debug Thiscommandrelaunchesthemostrecentlylaunchedapplicationunderdebuggercontrol,orlaunchestheselectedresourceoractiveeditordependingon
thelaunchoperationpreferencesettingsfoundontheRun/Debug>Launchingpreferencepage
Debugger
LocalDebugging
RemoteDebugging
RunningandDebugging
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
Linebreakpoints
Settingmethodbreakpoints
Catchingexceptions
DebugView
DebugPreferences
LaunchingPreferences
Runmenuactions
5.2.11.Javaeditor
Toolbaractions
Toolbar
Command Description
Button
ToggleJavaEditor ThisbuttonenablestheJavaeditorbreadcrumb.
Breadcrumb
Theenablementisrememberedforeachperspectiveseparately.
ToggleMarkOccurrences TurnsmarkoccurrencesonandoffintheJavaeditor.
ToggleBlockSelection Thisbuttonenablesblock(akacolumn)selectionmodeintheeditor.
Mode
ShowWhitespace Thisbuttonenablesthedisplayofwhitespacecharactersinaneditor.
Characters
ShowSourceofSelected Thisbuttonenableddisplayofasegmentedviewofthesourceofacompilationunit.
ElementOnly
ThisbuttonisonlyshownifyoucustomizeyourperspectivetoshowtheEditorPresentationactions.
Forexample,ifamethodisselectedintheOutlineview,theShowSourceOfSelectedElementOnlyoptioncausesonlythatmethod
tobedisplayedintheeditor,asopposedtotheentireclass.
Off:Theentirecompilationunitisdisplayedintheeditor,withtheselectedJavaelementhighlightedinthemarkerbarwitharange
indicator.
On:OnlytheselectedJavaelementisdisplayedintheeditor,whichislinkedtotheselectionintheOutlineorTypeHierarchyview.
GotoNextProblem Thiscommandnavigatestothenextproblemmarkerintheactiveeditor.
GotoPreviousProblem Thiscommandnavigatestothepreviousproblemmarkerintheactiveeditor.
Keybindingactions
Thefollowingactionscanonlybereachedthroughkeybindings.TheKeybindingsfieldinWindow>Preferences>General>Keysmustbesetto'Emacs'.
Keybinding Description
Alt+0Ctrl+K,Esc0Ctrl+K Deletesfromthecursorpositiontothebeginningoftheline.
Ctrl+K Deletesfromthecursorpositiontotheendoftheline.
Ctrl+Space,Ctrl+2 Setsamarkatthecurrentcursorposition.
Ctrl+XCtrl+X Swapsthecursorandmarkpositionifany.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 158/322
12/10/2015 Javadevelopmentuserguide
Javaeditor
Openinganeditorforaselectedelement
Javaoutline
Javaeditorpreferences
JDTactions
Viewsandeditors
5.3.1.JavaPreferences
ThefollowingJavapreferencescanbesetonthe Javapreferencepageanditssubpages.
Appearance
BuildPath
CodeStyle
Compiler
Debug
Editor
InstalledJREs
JUnit
PropertiesFileEditor
Actionondoubleclickin Expandtheselectedelement
thePackageExplorer Gointotheselectedelement
Whenyoudoubleclickacontainer,aGoIntocommandisexecuted.
SeeGoIntofromtheNavigatemenu.
Expandtheselectedelement
Whenyoudoubleclickacontainer,itisexpandedanditschildrenarerevealed.
WhenopeningaType ShowtheTypeHierarchyView
Hierarchy OpenanewTypeHierarchyPerspective inthecurrentperspective
OpensanewTypeHierarchyperspectivewheneveraTypeHierarchyviewisopened.
ShowtheTypeHierarchyViewinthecurrentperspective
TheTypeHierarchyviewisdisplayedinthecurrentperspective.
Note:OntheWorkbenchpreferencespage,youcanchoosewhethernewperspectivesopeninanewwindow,inthe
currentwindow,orasareplacementforthecurrentperspective.
RefactoringJavacode Off
Saveallmodifiedresourcesautomaticallypriortorefactoring
Ifthisoptionisturnedoff,refactoringsmayprompttosavemodifiedfilesifrequired.Ifitisturnedon,all
modifiedfilesaresavedwithoutpromptingpriortoopeningarefactoringwizard.
On
Renameineditorwithoutdialog
Ifthisoptionisturnedon,thentherenamerefactoringwillnotshowadialogifinvokedinsideaJavaeditor.
Insteadthenewnamefortheelementtorenamecanbetypedintotheeditorrightaway.
Search On
Usereducedsearchmenu
Ifthisoptionisturnedon,thesearchcontextmenusshowonlythemostfrequentlyusedsearchactions.
Javadialogs Button
Clearall'donotshowagain'settingsandshowallhiddendialogsagain
Ifpressed,all'donotshow'settingsarecleared.
Javaviews
PackageExplorerview
TypeHierarchyview
5.3.1.1.JavaAppearancePreferences
TheappearanceofJavaelementsinviewscanbeconfiguredonthe Java>Appearancepreferencepageandonitssubpages:
Membersortorder
Typefilters
Theoptionsare:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 159/322
12/10/2015 Javadevelopmentuserguide
Showmethodtypeparameters Ifenabled,methodsdisplayedinviewsshowtheirtypeparameters. On
Showcategories Ifenabled,method,fieldandtypelabelscontainthecategoriesspecifiedintheirJavadoccomment. On
ShowmembersinPackageExplorer Ifenabled,JavaelementsbelowthelevelofJavafilesandClassfilesaredisplayedaswell. On
Foldemptypackagesinhierarchicallayout Ifenabled,emptypackageswhichdonotcontainresourcesorotherchildelementsarefolded. On
Note:TheColoredLabelssettingsisnowavailableonthe General>Appearancepreferencepage.
Javaviews
PackageExplorerview
5.3.1.1.1.MemberSortOrderPreferences
IndicateyourpreferencesfortheMemberSortOrdersettingsonthe Java>Appearance>MemberSortOrderpreferencepage.
ThissettingsareusedbyJavaviewsaswellasbytheSortMembersAction.
Choosetheorderinwhichmemberswill Types,StaticFields,StaticInitializers,StaticMethods,Fields,
bedisplayed. Up Initializers,Constructors,Methods
Movemembersofselectedcategoryclosertothe
beginningofatype.
Down
Movemembersofselectedcategoryclosertotheend
ofatype.
Javaviews
PackageExplorerview
SourceActions
5.3.1.1.2.TypeFiltersPreferences
IndicateyourpreferencesfortheTypeFilterssettingsonthe Java>Appearance>TypeFilterspreferencepage.
Specifytypesandpackagestohideinthe'OpenType'dialogandcontentassistorquickfixproposalsonthispreferencepage.Ifaqualifiedtypenameorapackagematchoneof
thecheckedentriesinthelist,theywillbehidden.
Thedefaultistohidenothingbutforbiddenreferences.
Option Description
Add Addsanewentrytothelist.Entrieswillbecomparedagainstqualifiedtypename(usingdotsaspackagenameseparators)andcanusewildcards('*'and'?')
AddPackages Addsanewentrytothelistfromthelistofexistingpackagescurrentlyintheworkspace.
Edit Editsthecurrentlyselectedentry
Remove Removesthecurrentlyselectedentries
CheckAll Setsthecheckmarkonallentries
UncheckAll Removesthecheckmarkonallentries
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 160/322
12/10/2015 Javadevelopmentuserguide
AccessRestrictions
Option Description Default
Hideforbiddenreferences Ifenabled,referencestoJavaelementsforbiddenbyaccessrulesarenotdisplayed. On
Hidediscouragedreferences Ifenabled,referencestoJavaelementsdiscouragedbyaccessrulesarenotdisplayed. Off
Quickfix
AccessRules
Opentype
Content/Codeassist
5.3.1.2.JavaBuildPathPreferences
IndicateyourpreferencesfortheBuildPathsettingsonthe Java>BuildPathpreferencepageanditssubpages:
ClasspathVariables
UserLibraries
Theoptionsare:
Sourceandoutputfolder Folders
Project SourceFolder:src
UsetheprojectrootfolderasthefolderwhereJavasourcefilesandthegeneratedclassfilesarestoredbydefault. OutputFolder:bin
Folders
SpecifyseparatesourceandoutputfolderstostoretheJavasourcefilesseparatedfromthegeneratedclassfiles.
Classpathvariables
NewJavaprojectwizard
5.3.1.2.1.ClasspathVariablesPreferences
Configurablevariables
ClasspathvariablescanbeusedinaJavaBuildPathtoavoidareferencetothelocalfilesystem.Usingavariableentry,theclasspathonlycontainsavariableandthebuildpath
canbesharedinateam.Thevalueofsuchvariablesisconfiguredonthe Java>BuildPath>ClasspathVariablespreferencepage.
Command Description
New... Addsanewvariableentry.Intheresultingdialog,specifyanameandpathforthenewvariable.YoucanclicktheFileorFolderbuttonstobrowseforapath.
Edit... Allowsyoutoedittheselectedvariableentry.Intheresultingdialog,editthenameand/orpathforthevariable.YoucanclicktheFileorFolderbuttonstobrowsefor
apath.
Remove Removestheselectedvariableentry.
Reservedclasspathvariables
CertainclasspathvariablesaresetinternallyandcannotbechangedintheClasspathvariablespreferences:
JRE_LIB:ThearchivewiththeruntimeJARfileforthecurrentlyusedJRE.
JRE_SRC:ThesourcearchiveforthecurrentlyusedJRE.
JRE_SRCROOT:TherootpathinthesourcearchiveforthecurrentlyusedJRE.
Thesevariablesaredeprecatedandshouldnotbeusedanymore.InsteaduseaJRESystemLibrary.
Classpathvariables
InstalledJREs
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 161/322
12/10/2015 Javadevelopmentuserguide
5.3.1.2.2.UserLibrariesPreferences
IndicateyourpreferencesfortheUserLibrariessettingsonthe Java>BuildPath>UserLibrariespreferencepage.
AuserlibraryisasetofJARfiles.Auserlibrarycanbeaddedtoaprojectsbuildpaththroughthebuildpathpropertiespage.TheUserLibrariespreferencepageallowstodefine,
edit,import,export,orremoveuserlibraries.
Option Description
New... Createsanewuserlibrary
Edit... Editsthecurrentlyselectedlibrary,JARorJARattribute
Add AddsoneormoreJARstothecurrentlyselecteduserlibrary
JARs...
Remove.. RemovesthecurrentlyselecteduserlibraryorJAR
Up MovesthecurrentlyselectedJARupinthelistofJARsofauserlibrary.TheordercanbeimportantifmorethanoneJARcontainatypewiththesamequalified
name.
Down MovesthecurrentlyselectedJARdowninthelistofJARsofauserlibrary.TheordercanbeimportantifmorethanoneJARcontainatypewiththesamequalified
name.
Import... Addsnewlibrariesfromanimportfile
Export... Exportslibrariestoanimportfile
JavaBuildPathpage
5.3.1.3.JavaCodeStylePreferences
The Java>CodeStylepreferencepageallowstoconfigurenamingconventions,stylerulesandcommentsettings.Thesepreferencesareusedwhennewcodehastobe
generated.
Subpagesoffermorecodestylesettings:
CleanUp
CodeTemplates
Formatter
OrganizeImports
Theoptionsare:
NamingConventions
Thelistdefinesthenamingconventionsforfields(staticandnonstatic),parametersandlocalvariables.Foreachvariabletypeitispossibletoconfigurealistofprefixorsuffixor
both.
Namingconventionsareusedbyallactionsand'QuickFix'proposalsthatcreatefields,parametersandlocalvariables,inparticulartheSourceactions.
Action Description
Edit... Opensadialogtoeditthelistofprefixandsuffixesforthecurrently
selectedvariabletype
CodeConventions
Thefollowingsettingsspecifyhownewlygeneratedcodeshouldlooklike.Thenamesofgettermethodscanbespecifiedaswellastheformatoffieldaccesses,methodcomments,
annotationsandexceptionvariables.
Use'is'prefixfor Ifselected,thenamesofgettermethodsofbooleantypeare On
gettersthatreturn prefixedwith'is'ratherthan'get'.
boolean
Add'@Override' Ifselected,methodswhichoverrideanalreadyimplemented On
annotationforoverriding methodareannotatedwithan'@Override'annotation.Seethe
methods Compilerpreferencepageforsettingsrelatedtoannotations.
Exceptionvariable Specifythenameoftheexceptionvariabledeclaredincatch e
nameincatchblocks blocks.
Sourceactions
Javaeditor
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 162/322
12/10/2015 Javadevelopmentuserguide
Javaeditorpreferences
Javacompilerpreferences
Codetemplatespreferences
5.3.1.3.1.CleanUpPreferences
The Java>CodeStyle>CleanUppreferencepageletsyoumanageyourcodecleanupprofilesfortheJavacodecleanup.
Action Description
Activeprofile Selectstheprofileactivefortheworkspaceorcurrentproject.
Edit... Showsadialogwhichdisplaysthesettingsstoredintheactiveprofile.
Onlyuserdefinedprofilescanbemodified.
Remove Removestheselectedprofile.Thisactionisonlyavailableonuserdefined
profiles.
New... Showsthedialogtocreateanewprofile.Thedialogrequiresyoutoentera
nameforthenewprofile.Additionally,youmayselectabuiltinoruser
definedexistingprofiletobaseyournewprofileon.
Import... Importsprofilesfromthefilesystem.
ExportAll... Exportsalltheprofilestothefilesystem.
Details Displaysasummaryoftheenabledoptionsoftheactiveprofile
DisableShowprofileselectiondialogforthe'Source>CleanUp'actiontoapplytheactiveprofilewhenyouinvokeSource>CleanUpwithoutbeingdisturbedbyadialog.
Javaeditor
Javaeditorpreferences
5.3.1.3.2.CodeTemplatesPreferences
The Java>CodeStyle>CodeTemplatespreferencepageletsyouconfiguretheformatofnewlygeneratedcodeandcomments.
CodeandComments
Thecodeandcommentpagecontainscodetemplatesthatareusedbyactionsthatgeneratecode.Templatescontainvariablesthataresubstitutedwhenthetemplateisapplied.
Somevariablesareavailableinalltemplates,somearespecifictotemplates.
n/a
Edit... OpenstheCodeTemplatedialogtoeditthecurrentlyselected
codetemplate.
n/a
Import... Importscodetemplatesfromthefilesystem.
n/a
Export... Exportsallselectedcodetemplatestothefilesystem.
n/a
ExportAll... Exportsallcodetemplatestothefilesystem.
CommentTemplates
Commenttemplatescancontainthevariable${tags}thatwillbesubstitutedbythestandardJavadoctags(@param,@return..)forthecommentedelement.The'Overridingmethod'
commentcanadditionallycontainthetemplate${see_to_overridden}
TemplateName Specifies
Files Headercommentfornewfiles.
Notethatthistemplatecanbereferencedinthe'NewJavaFile'template
with${filecomment}.
Types Thecommentfornewtypes.
Notethatthistemplatecanbereferencedinthe'NewJavaFile'template
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 163/322
12/10/2015 Javadevelopmentuserguide
with${typecomment}.
Fields Thecommentfornewfields.
Constructors Thecommentfornewconstructors.
Methods Thecommentfornewmethodsthatdonotoverrideanmethodinabase
classandthatdonotdelegatetoanyothermethod.
Overridingmethods Thecommentfornewmethodsthatoverrideanmethodinabaseclass.
BydefaultthecommentisdefinedasanonJavadoccomment(Javadoc
willreplacethiscommentwiththecommentoftheoverriddenmethod).You
canchangethistoarealJavadoccommentifyouwant
Delegatingmethods Thecommentfornewmethodswhichdelegatetoexistingmethods.
SuchmethodscanbecreatedwiththeSource>GenerateDelegate
Methods...action.
Getters Thecommentforgettermethods.
Setters Thecommentforsettermethods.
CodeTemplates
TemplateName Description
NewJavafiles UsedbytheNewTypewizardswhenanewJavafileiscreated.
Thetemplatecanspecifywherecommentsareadded.Notethatthe
templatecancontainthevariable${typecomment}and${filecomment}
thatwillbesubstitutedbytheevaluationoftheTypesrespectivelyFiles
commenttemplate.
Classbody UsedbytheNewClasswizardswhenanewJavaclassiscreated.
Interfacebody UsedbytheNewInterfacewizardswhenanewJavainterfaceiscreated.
Enumbody UsedbytheNewEnumwizardswhenanewJavaenumiscreated.
Annotationbody UsedbytheNewAnnotationwizardswhenanewJavaannotationis
created.
Methodbody The'Methodbody'templatesareusedwhennewmethodwithabodyis
createdthatstillneedssomecodetocompleteitsfunctionality.
Itcontainsthevariable${body_statement}thatresolvestoareturn
statementor/andasupercall.
Constructorbody The'Constructorbody'templatesareusedwhennewmethodor
constructorwithbodyiscreated.
Itcontainsthevariable${body_statement}thatresolvesasupercall.
Getterbody The'Getterbody'templatesareusedwhennewgettermethodiscreated.
Itcontainsthevariable${body_statement}thatresolvestotheappropriate
returnstatement.
Setterbody The'Setterbody'templatesareusedwhennewsettermethodiscreated.
Itcontainsthevariable${body_statement}thatresolvestotheappropriate
assignmentstatement.
Catchblockbody The'Catchblockbody'templateisusedwhenacatchblockbodyis
created.
Itcanusethevariables${exception_type}and${exception_var}.
CodeTemplatedialog
Thefollowingfieldsandbuttonsappearinthedialog:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 164/322
12/10/2015 Javadevelopmentuserguide
Action Description
Description Adescriptionofthetemplate
Pattern Thetemplatepattern.
InsertVariables... Displaysalistofpredefinedtemplatespecificvariables.
Templatevariables
Sourceactions
Javaeditor
Javaeditorpreferences
Templatespreferences
5.3.1.3.3.CodeFormatterPreferences
The Java>CodeStyle>FormatterpreferencepageletsyoumanageyourcodeformatterprofilesfortheJavacodeformatter.
Action Description
Activeprofile Selectstheprofileactivefortheworkspaceorcurrentproject.
Edit... Showsadialogwhichdisplaysthesettingsstoredintheactiveprofile.
Onlyuserdefinedprofilescanbemodified.
Remove Removestheselectedprofile.Thisactionisonlyavailableonuserdefined
profiles.
New... Showsthedialogtocreateanewprofile.Thedialogrequiresyoutoentera
nameforthenewprofile.Additionally,youmayselectabuiltinoruser
definedexistingprofiletobaseyournewprofileon.
Import... Importsprofilesfromthefilesystem.
ExportAll... Exportsalltheprofilestothefilesystem.
Details DisplaysasamplehowtheactiveprofileformatsaJavacodesnippet
Tochangeyourformatteroptionsyoucaneitherselectoneofthebuiltinprofilesorcreateanewprofile.TocreateanewprofileselectNew....Youcantheneditthenewprofileby
selectingEdit....
Ifyourprojectisshared,e.g.throughCVS,andusesaformatterprofilewhichisnotmanagedbyyourself(youhavenotcreatedtheprofile)thentheprofilewillbemarkedas
UnmanagedProfile.Youarenotallowedtochangesuchaprofile,onlythecreator(manager)oftheprofilecanchangeit.
Javaeditor
Javaeditorpreferences
5.3.1.3.4.OrganizeImportsPreferences
The Java>CodeStyle>OrganizeImportspreferencepagedefineshowtheOrganizeImportscommandgeneratestheimportstatementsinacompilationunit.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 165/322
12/10/2015 Javadevelopmentuserguide
Up Movestheselectedpackagenameprefixupintheimportorderlist. n/a
Numberofimportsneededfor.* Thenumberofimportstatementsthatareallowedfortypesinthesamepackagebefore<package>.*isused. 99
Numberofstaticimportsneededfor.* Thenumberofstaticimportstatementsthatareallowedforstaticmembersofthesametypebeforetypeisused. 99
Donotcreateimportsfortypesstartingwith Ifenabled,typesstartingwithalowercaseletterarenotimported. On
alowercaseletter
Sourceactions
5.3.1.4.JavaCompilerPreferences
The Java>CompilerpreferencepageletsyouconfigurethevarioussettingsrelatedtocompilingofJavasourcecodeandclassfilegeneration.
AnEclipsebasedproductmaychangethecompilerdefaults,sotheymaybedifferentthantheonesindicatedhere.
Subpagesoffermorecompilersettings:
Building
Error/Warnings
Javadoc
TaskTags
Theoptionsare:
JDKCompliance
Usedefaultcompliance Ifenabled,thedefaultcompliancesettingsforthecompilercompliancelevelareapplied. On
settings
Classfilegeneration
Addvariableattributesto Ifenabled,variableattributesareaddedtotheclassfile.Thiswillenablelocalvariablenamestobedisplayedinthedebugger(inplaces On
generatedclassfiles wherevariablesaredefinitelyassigned)Theresulting.classfileisthenbigger.
Addlinenumberattributesto Ifenabled,linenumberinformationisaddedtotheclassfile.Thiswillenablesourcecodehighlightinginthedebugger. On
generatedclassfiles
Addsourcefilenameto Ifenabled,thesourcefilenameisaddedtotheclassfile.Thiswillenablethedebuggertopresentthecorrespondingsourcecode. On
generatedclassfile
Preserveunusedlocalvariables Ifenabled,unusedlocalvariables(i.e.neverread)arenotstrippedfromtheclassfile.Ifstrippedthispotentiallyaltersdebugging. On
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 166/322
12/10/2015 Javadevelopmentuserguide
parameters
Javabuilder
WorkingwithJREs
Classpathvariablespreferences
Javabuildpathproperties
Buildingpreferencepage
Errors/Warningspreferencepage
Javadocpreferencepage
Tasktagspreferencepage
5.3.1.4.1.JavaBuildingPreferences
IndicateyourpreferencesfortheBuildingsettingsonthe Java>Compiler>Buildingpreferencepage.
General
Enableuseofexclusionpatternsinsource Whendisabled,noentryonaprojectclasspathcanbeassociatedwithanexclusionpattern. On
folders
Enableuseofmultipleoutputlocationsfor Whendisabled,noentryonaprojectclasspathcanbeassociatedwithaspecificoutputlocation,preventingthususage On
sourcefolders ofmultipleoutputlocations.
Buildpathproblems
Abortbuildwhenbuild Allowtotogglethebuildertoabortiftheclasspathisinvalid. On
patherrorsoccur
Outputfolder
Scruboutputfolderswhencleaning IndicatewhethertheJavaBuilderisallowedtocleantheoutputfolderswhenperformingfullbuildoperations. On
projects
Javabuilder
Inclusionandexclusionpatterns
Buildclasspath
5.3.1.4.2.JavaCompileErrors/WarningsPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 167/322
12/10/2015 Javadevelopmentuserguide
IndicateyourpreferencesfortheErrors/Warningssettingsonthe Java>Compiler>Errors/Warningspreferencepage.
Codestyle
Potentialprogrammingproblems
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 168/322
12/10/2015 Javadevelopmentuserguide
Signalevenif Whenenabled,thecompileradditionallywillissueanerrororawarningifanenumconstantisnotcoveredbyacase,evenifa'default'case Off
'default'caseexists exists.
Thisoptionhelpstocatchmissingcasestatementswhenanewenumconstantisadded.
Whenenabled,thecompilerwillissueanerrororawarningforhiddencatchblockscorrespondingtocheckedexceptions.
Nameshadowingandconflicts
DeprecatedandrestrictedAPI
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 169/322
12/10/2015 Javadevelopmentuserguide
SignaluseofdeprecatedAPIinside Whenenabled,thecompilerwillsignaluseofdeprecatedAPIinsidedeprecatedcode.Theseverityoftheproblemis Off
deprecatedcode controlledwithoption"DeprecatedAPI".
Unnecessarycode
Ignoreinoverridingandimplementing Whenenabled,thecompilerwillnotissueanerrororawarningwheneveraparameterisdeclaredbutneverusedwithinits On
methods scopeinamethodthatoverridesorimplementsanothermethod.
Ignoreparametersdocumentedwith Whenenabled,thecompilerwillnotissueanerrororawarningwheneveranunreadparameterisdocumentedwithan On
'@param'tag '@param'tag.
Ignoreinoverridingandimplementing Whenenabled,thecompilerwillnotissueanerrororawarningwheneveritencountersanunnecessarydeclarationofa On
methods thrownexceptioninamethodthatoverridesorimplementsanothermethod.
Ignoreexceptionsdocumentedwith Whenenabled,thecompilerwillnotissueanerrororawarningwheneveranunnecessarydeclarationofathrownexception On
'@throws'or'@exception'tags isdocumentedwithan'@throws'or'@exception'tag.
Ignore'Exception'and'Throwable' Whenenabled,thecompilerwillnotissueanerrororawarningwheneveritencountersanunnecessarydeclarationof On
'Exception'and'Throwable'exception
Generictypes
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 170/322
12/10/2015 Javadevelopmentuserguide
duetorawAPIs methodsitoverridesfromasupertypearedeclaredtouserawtypesinthefirstplace.
WhentheoldAPIiseventuallygenerified,thenmostoftheseproblemseithergoaway,oryouwillseeacompileerrorbecausethetype
argumentsyouusedarenotcorrect.Forrawreferencesinmethodsignatures,therawtypeproblemwillreappear.
Annotations
Includeimplementationsofinterface Whenenabled,thecompilerwillalsoissueanerrororawarningwheneveritencountersamethodoverridingorimplementinga On
methods(1.6orhigher) methoddeclaredinaninterface,andthe'@Override'annotationismissing.
Notethat'@Override'isonlyallowedonsuchmethodsifthecompilercompliancelevelis1.6orhigher,sothiserrororwarning
willneverappearin1.5code.
Enable'@SuppressWarnings' Whenenabled,thecompilerwillprocess'@SuppressWarnings'annotations.Whendisabled,itwillactasifall On
annotations '@SuppressWarnings'annotationswereremoved.
Nullanalysis
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 171/322
12/10/2015 Javadevelopmentuserguide
Uncheckedconversion Dependingonthisoption,thecompilerwillissueeitheranerrororawarningwheneveroneofthefollowingsituationsisdetected: Warning
fromnonannotatedtypeto
@NonNulltype 1. Amethoddeclaredwithanonnullannotationreturnsanexpressionforwhichinsufficientnullnessinformationisavailablefor
staticallyprovingthatnoflowwillpassanullvalueatruntime.
2. Anexpressionforwhichinsufficientnullnessinformationisavailableforstaticallyprovingthatitwillneverevaluatetoanullvalue
atruntimeispassedasanargumentinamethodcallwherethecorrespondingparameterofthecalledmethodisdeclaredwitha
nonnullannotation.
3. Anexpressionforwhichinsufficientnullnessinformationisavailableforstaticallyprovingthatitwillneverevaluatetoanullvalue
atruntimeisassignedtoalocalvariablethatisdeclaredwithanonnullannotation.
Uncheckedconversionisusuallyaconsequenceofusingotherunannotatedvariablesormethods.
Usedefaultannotationsfor Whenenabled,thecompilerwillusethedefaultsetofannotationsfornullspecifications.TheseannotationsareincludedintheEclipse On
nullspecifications SDKintheorg.eclipse.jdt.annotationbundle.
Youcanspecifydifferentannotationnamestouseinyourprojects,butbeawarethattheEclipsecompileronlysupportsthesemantics
specifiedinthedefaultannotations:
org.eclipse.jdt.annotation.Nullable:AfullyqualifiednameofaJavaannotationtype,whichwhenappliedtoatypeinamethod
signature,variabledeclarationorfielddeclaration,willbeinterpretedasaspecificationthatnullisalegalvalueinthatposition.
Currentlysupportedpositionsare:methodparameters,methodreturntype,localvariablesandfields.
org.eclipse.jdt.annotation.NonNull:AfullyqualifiednameofaJavaannotationtype,whichwhenappliedtoatypeinamethod
signature,variabledeclarationorfielddeclaration,willbeinterpretedasaspecificationthatnullisnotalegalvalueinthatposition.
Currentlysupportedpositionsare:methodparameters,methodreturntype,localvariablesandfields.
org.eclipse.jdt.annotation.NonNullByDefault:AfullyqualifiednameofaJavaannotationtype.Whenappliedtoanelement
withoutanannotationargument,allunannotatedtypesinmethodsignatureswithintheannotatedelementwillbetreatedasifthey
werespecifiedwiththenonnullannotation.
Onthecontrary,whentheannotationisappliedwiththeconstant'false'asitsargument,allcorrespondingdefaultsatouterscopes
willbecanceledfortheannotatedelement.
WhenTreataboveerrorslikefatalcompileerrorsisenabled,allgeneratederrors,fatalorconfigurable,leadtononexecutablecode.Ifdisabled,thenyourcodecanbeexecuted
aslongasithasnofatalerror(syntaxerror,typeerror,oranyerroraccordingtotheJavaLanguageSpecification).
ProblemsView
QuickFix
Javabuilder
5.3.1.4.3.JavaCompilerJavadocPreferences
IndicateyourpreferencesfortheJavadocsettingsonthe Java>Compiler>Javadocpreferencepage.
ProcessJavadoccomments(includes ThebuilderdetectsproblemsinJavadoccommentsifthisoptionisenabled.Forsearchandrefactoringtoworkon On
searchandrefactoring) Javadoccommentsitisalsorequiredtoenablethisoption.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 172/322
12/10/2015 Javadevelopmentuserguide
Validatetagarguments(@param, Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersanerrorinaJavadoccommenttag Off
@throws,@exception,@see,@link) argumentfor@param,@throws,@exception,@seeor@link.
Ignoreinoverridingandimplementing Whenenabled,methodsthatoverrideorimplementanothermethodarenotcheckedformissingJavadoctags. On
methods
Ignoremethodtypeparameters Whenenabled,missingJavadoctagsarenotreportedformethodtypeparameters. On
Ignoreinoverridingandimplementing Whenenabled,methodsthatoverrideorimplementanothermethodarenotcheckedformissingJavadoccomments. On
methods
5.3.1.4.4.JavaTaskTagsPreferences
Tasktagscanbeconfiguredonthe Java>Compiler>TaskTagspreferencepage.Whenthetaglistisnotempty,thecompilerwillissueataskmarkerwheneveritencounters
oneofthecorrespondingtaginsideanycommentinJavasourcecode.Generatedtaskmessageswillincludethetag,rangeuntilthenextlineseparator,commentendingornon
emptytag,andwillbetrimmed.Ifthesamelineofcodecarriesmultipletags,theywillbereportedseparately.
SeetheCompilerpreferencepageforinformationonhowtoenabletasktagsinyoursourcecode.
Action Description
New... Addsanewtasktag.Intheresultingdialog,specifyanameandpriorityforthenewtasktag.
Remove Removestheselectedtasktag.
Edit... Allowsyoutoedittheselectedtasktag.Intheresultingdialog,editthenameand/orpriorityforthetasktag.
Default Setsthecurrentlyselectedtasktagasthedefaulttasktag.ThedefaulttasktagistheonethatisusedinthecodetemplatesasspecifiedontheCodeTemplates
preferencepage.Thedefaulttasktagisdisplayedinboldfont.
CasesensitivityofthetasktagscanbespecifiedatthebottomofthepreferencepageusingtheoptionCasesensitivetasktagnames.
Javacompilerpreferences
Codetemplatepreferences
5.3.1.5.JavaDebugPreferences
Thefollowingpreferencescanbesetusingthe Java>Debugpreferencepage.
Theseoptionsapplytojavaspecificdebuggersandhavetodowithsuspendingoptionsandhotcodereplace.
Suspendexecutiononuncaught On
exceptions Thisoptioncontrolsifaprogramwillsuspendifanuncaughtexceptionisthrown.
ForexampleifyoutrytocallamethodonanullobjectandaNullPointerExceptionisthrown,withthisoptiononyourprogramwill
suspendatthelocationtheexceptionwasthrown
Suspendexecutiononcompilation Thisoptioncontrolsifaprogramwillsuspendwhenacompilationerrorisencountered On
errors
Suspendforbreakpointsduring Thisoptionscontrolsifbreakpointswillsuspendduringanevaluationofcodecontainingabreakpoint.Formoreinformationabout On
evaluations evaluationsgohere
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 173/322
12/10/2015 Javadevelopmentuserguide
Openpopupwhensuspendedon Thisoptioncontrolsifapopupwindowwillbedisplayedwhenexecutionofaprogramstopsonanexception.Theexceptionthe Off
exception programsuspendedonismadeavailableforinspectioninthepopup
Defaultsuspendpolicyfornew Thisoptionallowsthedefaultsuspendpolicytobesetfornewbreakpoints.Thesuspendpolicyisusedbybreakpointstotellthe Suspend
breakpoints VMwhattosuspend,inthiscaseeitherthethreadthebreakpointisactiveinortheentirerunningVM Thread
Defaultsuspendpolicyfornew Thisoptionallowsthedefaultsuspendpolicytobesetfornewwatchpoints.Thesuspendpolicyisusedbywatchpointstotellthe Suspend
watchpoints VMwhatkindoffieldactionstosuspendoninthiscaseeitheraccessandmodification(both),accessonlyormodificationonly Thread
Showerrorwhenhotcodereplace Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenahotcodereplacefails On
fails
Showerrorwhenhotcodereplace Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenhotcodereplaceisnotsupported,andtheuserhas On
isnotsupported madeandsavedchangestocurrentlyrunningcode
Showerrorwhenobsoletemethods Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenahotcodereplacecompleted,buttherewereobsolete On
remainafterhotcodereplace methodsleftover
Replaceclassfilescontaining Thisoptioncontrolsisclassfilescontainingcompilationerrorswillbereplaced On
compilationerrors
Debuggertimeout Thisoptiondescribesthelengthoftime(inmilliseconds)thedebuggerwillwaittryingtocommunicatewitharunningVMbefore 3000
givingupanddisconnecting
Launchtimeout Thisoptiondescribesthelengthoftime(inmilliseconds)thatalaunchwillwaittocompletethelaunchingprocessbeforegivingup 20000
andterminating.Thisoptionhasnobearingonthelengthoftimeaprogramwillrun,onlyhowlongtheprocessoftryingtoruna
programwillwait
Warnwhenunabletoinstall Thisoptioncontrolsiftheuserwillbenotifiediftheytrytosetalinebreakpointonalinethathasinvalidlineinformation On
breakpointduetomissingline
numberattributes
Promptforconfirmationwhen Thisoptioncontrolsifclientsshouldbepromptedwhentryingtoremoveabreakpointwithaconditionfromtheeditor On
deletingaconditrionalbreakpoint
fromtheeditor
Onlyincludeexportedclasspath Thisoptioncontrolsifonlyclasspathentriesmarkedasexportedshouldbeincludedintheclasspathusedforlaunching Off
entrieswhenlaunching
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences
5.3.1.5.1.DetailFormattersPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>DetailFormatterspreferencepage.
Thesepreferencesareusedtocreateandmanagedetailformatters,whichareusedinthedetailspanesofvariablesviews,orforvariablelabelsthemselves.
Typeswithdetailformatters Thelistingoftypesthatcurrentlyhavedetailformatters(thelistitself),andtheenabledstateofthedetailformatter,i.e.ifitisonuse
(thecheckedstateofalistitem)
Addbutton Usedtoaddanewdetailformattertothecurrentlisting
Editbutton Usedtoedittheselecteddetailformatter
Removebutton Usedtoremovetheselecteddetailformatter
Detailformattercodesnippetfor Displaysthecurrentcodesnippetinuseforthedetailformatteroftheselectedtype.Thisfieldisnoteditable,theonlywaytoedita
selectedtype detailformatteristousetheEdit...button
Showvariablesdetails
Thisoptioncontrolswhereyouwanttoseethedetailformatterappear,youhaveoneofthreechoices:
Asalabelforvariableswithdetailformatterswillappearastheprimarydisplaylabelonlyforassociatedvariablesthehave
detailformatters
Asalabelforallvariableswillappearforallassociatedvariables,regardlessofthemhavingdetailformattersalready
Indetailpaneonlywillonlyappearinvariablesviewdetailspanesandnowhereelse
Debugger
Javaperspectives
Javaviews
Localdebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 174/322
12/10/2015 Javadevelopmentuserguide
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences
5.3.1.5.2.HeapWalkingPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>HeapWalkingpreferencepage.
ThesepreferencesallowcountsettingsforJava1.6heapwalkingfeaturestobechanged.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DetailFormattersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences
5.3.1.5.3.LogicalStructuresPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>LogicalStructurespreferencepage.
Thesepreferencesareusedtoadd,editandremovelogicalstructures,whichareusedtodisplaycollectiontypeobjects
LogicalStructures Showsalistingofallofthecurrentlogicalstructuresavailable.Notethatlogicalstructureswithayellowbackgroundcannotbeeditedorremoved
Addbutton Usedtoaddanewlogicalstructuretothelisting
Editbutton Usedtoedittheselectedlogicalstructure
Removebutton Usedtoremovetheselectedlogicalstructure
Preview Showsthecodesnippettotheselectedlogicalstructure.Thispreviewisnoteditable,youmustusetheEdit...buttontoeditalogicalstructure
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 175/322
12/10/2015 Javadevelopmentuserguide
JavaDebugPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences
5.3.1.5.4.PrimitiveDisplayOptionsPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>PrimitiveDisplayOptionspreferencepage.
Thesepreferencesaffecthowprimitivevaluesaredisplayed(int,double,etc).
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
Run/DebugPreferences
StepFilteringPreferences
5.3.1.5.5.StepFilteringPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>StepFilteringpreferencepage.
Thesepreferencesareusedtoconfigurestepfiltersandstepfilteringoptions.
Usestep Thisoptioncontrolsisstepfilteringshouldbeenabledornot.SeealsothestepfilteringcommandintheDebugView On
filters
Defined Thisisalistingofallofthedefinedstepfilters(thelistingitself)andwhetherthestepfiltersareinuseornot(thecheckedstateofstepfilter)
stepfilters
AddFilter Usedtoaddanewstepfilterthatisbasedonaregularexpression
button
AddClass UsedtoaddanewJavaclasstothelistingofstepfilters
button
Add UsedtoaddnewJavapackagestothelistingofstepfilters
Packages
button
Remove Usedtoremovetheselectedstepfilter(s)
button
SelectAll Usedtosetalldefinedstepfiltersasenabled(orchecked)
button
DeselectAll Usedtosetalldefinedstepfiltersasdisabled(orunchecked)
button
Filter Thisoptioncontrolsifsyntheticmethodshouldalwaysbefilteredornotwhilestepping.ThisoptionrequiresthattheVMusedsupportsyntheticmethods Off
synthetic
methods
Filterstatic Thisoptioncontrolsifstaticinitializersshouldalwaysbefilteredornotwhilestepping Off
initializers
Filtersimple ThisoptioncontrolsifsimpleJavabeanstylegettersshouldalwaysbefilteredornotwhilestepping Off
getters
Filtersimple ThisoptioncontrolsifsimpleJavabeanstylesettersshouldalwaysbefilteredornotwhilestepping Off
setters
Filter Thisoptioncontrolsifconstructorsshouldalwaysbefilteredornotwhilestepping Off
constructors
Step On
through Thisoptioncontrolsstepfilterstoalwaysreturnfromafilteredlocationorstepthroughtoanonfilteredlocation.
filters Forexample,ifjava.utilisafilteredlocation,steppingintocodeinHashMapcouldresultinacallbacktoyourapplicationcodetochecktheequalityofan
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 176/322
12/10/2015 Javadevelopmentuserguide
object.IfyouchoosetoStepthroughfiltersastepintowouldendupinyourapplicationcode.However,whentheStepthroughfiltersoptionisdisabled,
astepintoHashMapwouldbehavelikeastepover.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
5.3.1.6.JavaEditorPreferences
ThefollowingJavaeditorpreferencescanbesetonthe Java>Editorpreferencepageanditssubpages.
ContentAssist
Advanced
Favorites
Folding
Hovers
MarkOccurrences
SaveActions
SyntaxColoring
Templates
Typing
Notethatsomeoptionsthataregenerallyapplicabletotexteditorscanbeconfiguredonthetexteditorpreferencepage.
Reportproblemsasyoutype
Ifenabled,theeditormarkserrorsandwarningsasyoutype,evenifyoudonotsavetheeditorcontents.The On
problemsareupdatedafterashortdelay.
Brackethighlighting
Ifenabled,theJavaeditorhighlightsparenthesis,bracketorcurlybraces,basedonwhichsuboptionisselected. On
ThecolorofthebrackethighlightisspecifiedwithAppearancecoloroptions.
Matchingbracket
Ifenabled,wheneverthecursorisnexttoabracket,itsopeningorclosingcounterpartishighlighted. On
Matchingbracketandcaretlocation
Ifenabled,wheneverthecursorisnexttoabracket,boththebracketanditsopeningorclosingcounterpartare Off
highlighted.
Enclosingbrackets
Ifenabled,theJavaeditorhighlightstheclosestbracketpairenclosingthecursor. Off
Lightbulbforquickassists
Ifenabled,a showsupintheverticalrulerwheneveraquickassistisavailable.Seethequickassistsection Off
foralistoftheavailableassists.
OnlyshowtheselectedJavaelement
Ifenabled,theJavaeditorwillonlyshowtheselectedJavaelementwhichiscurrentlyselected(i.e.intheOutline Off
VieworthePackageExplorer).
Appearancecoloroptions
ThecolorsofvariousJavaeditorappearancefeaturesarespecifiedhere. default
colors
Matchingbracketshighlight
Thecolorofbracketshighlight.
Parameterhintsbackground
Thebackgroundcoloroftheparameterhintwindow
Parameterhintsforeground
Theforegroundcoloroftheparameterhintwindow
Completionoverwritebackground
Thebackgroundcolorofthecompletionoverwritewindow
Completionoverwriteforeground
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 177/322
12/10/2015 Javadevelopmentuserguide
Theforegroundcolorofthecompletionoverwritewindow
Sourcehoverbackground
Thebackgroundcolorforthesourcehover.Thesourcehovershowsthesourcecodeoftheelementunder
themousepointer.
Javaeditor
Javaeditor
Codeformatterpreferences
Javaoutline
Javacontentassist
QuickFix
QuickAssist
5.3.1.6.1.JavaContentAssistPreferences
IndicateyourpreferencesfortheContentAssistsettingsonthe Java>Editor>ContentAssistpreferencepage.
Insertion
Completioninserts/Completion IfCompletioninsertsison,thecompletiontextisinsertedatthecaretposition,soitneveroverwritesanyexistingtext. Completion
overwrites IfCompletionoverwritesison,thecompletiontextreplacesthecharactersfollowingthecaretpositionuntiltheendoftheword. inserts
NotethatpressingCtrlwhenapplyingacompletionproposaltogglesbetweenthetwoinsertionmodes.
Insertsingleproposals Ifenabled,codeassistwillchooseandinsertautomaticallysingleproposals. On
automatically
Insertcommonprefixes Ifenabled,codeassistwillautomaticallyinsertthecommonprefixofallpossiblecompletionssimilartoUnixshellexpansion.This Off
automatically canbeusedrepeatedly,evenwhilethecodeassistwindowisbeingdisplayed.
Addimportinsteadofqualified Ifenabled,typeproposalswhichareinotherpackageswillinvoketheadditionofthecorrespondingimportdeclaration.Otherwise, On
name thetypewillbeinsertedfullyqualified.
Usestaticimports Ifenabled,methodproposalsforstaticmethodswillinvoketheadditionofthecorrespondingstaticimportdeclaration.Otherwise,a On
nonstaticimportforthedeclaringtypewillbeadded.
AddthemethodortypecontainingthemethodtotheFavoritespreferencepagetogetaproposalforsuchmethods.
Fillmethodargumentsandshow Ifenabled,codeassistwilladdargumentwhencompletingamethod.Itwillalsooffermatchingvariables,fieldsormethod On
guessedarguments invocationsfromthecontextwhereamethodproposalisinserted.
Insertparameternames Ifselected,codeassistwillfilltheargumentswiththeparameternamesusedinthemethoddeclaration. Off
Insertbestguessedarguments Ifselected,codeassistwillfilltheargumentswiththebestmatchingvariable,fieldormethodinvocationfromthecontextwherea Off
methodproposalisinserted.
SortingandFiltering
ConfigureTypeFilters.
Sortproposals Selecthowtheproposalsshouldbesortedinthecontentassistpopup. by
relevance
Showcamelcasematches Ifenabled,camelcasematchesaredisplayed(i.e.NPEisexpandedtoNullPointerException). On
Hideproposalsnotvisibleinthe Ifenabled,theJavaelementproposalsarelimitedbytherulesofvisibility.Forexample,privatefieldproposalsofotherclasses On
invocationcontext wouldnotbedisplayed.
Hidedeprecatedreferences Ifenabled,referencestodeprecatedJavaelementsarenotdisplayed. Off
AutoActivation
Enableautoactivation Ifenabled,codeassistcanbeinvokedautomatically. On
TheconditionforautomaticinvocationisspecifiedwiththepreferencesAutoactivationdelay,AutoactivationtriggersforJava
andAutoactivationtriggersforJavadoc.
Content/CodeAssist
TypeFilters
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 178/322
12/10/2015 Javadevelopmentuserguide
5.3.1.6.1.1.AdvancedJavaContentAssistPreferences
IndicateyourpreferencesfortheAdvancedsettingsonthe Java>Editor>ContentAssist>Advancedpreferencepage.
Content/CodeAssist
ContentAssistpreferencepage
5.3.1.6.1.2.JavaContentAssistFavoritesPreferences
Indicateyourpreferencessettingsforthecontentassistforstaticmembersonthe Java>Editor>ContentAssist>Favoritespreferencepage.
Youcandefinealistofstaticmembersandtypescontainingstaticmembersonthispage.Contentassistwillproposethosememberseveniftheimportismissing.
Toseethestaticimportproposals,makesureUsestaticimportsisenabledonthe ContentAssistpreferencepage
Action Description
NewType Addanewtypetothelist.Allstaticmembersdeclaredbytheaddedtypewillbeproposedbycontentassist.
NewMember Addastaticmembertothelist.Thememberwillbeproposedbycontentassist.
Edit Edittheselectedentry.
Remove Removestheselectedentryfromthelist.
Content/Codeassist
Contentassistpreferencepage
5.3.1.6.2.JavaEditorFoldingPreferences
IndicateyourpreferencesfortheFoldingsettingsonthe Java>Editor>Foldingpreferencepage.
Enablefolding Ifenabled,differentsectionsintheJavaeditorcanbefoldedandexpanded. On
HeaderComments Ifenabled,headerCommentsarefoldedwhenopeninganeweditor. On
Imports Ifenabled,importsarefoldedwhenopeninganeweditor. On
JavaEditorpreferencepage
5.3.1.6.3.JavaHoversPreferences
IndicateyourpreferencesfortheHoverssettingsonthe Java>Editor>Hoverspreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 179/322
12/10/2015 Javadevelopmentuserguide
Expandverticalruler Ifenabled,whentherearemultipleiconsperlineshownonverticalruler,thentheiconsareexpandedwhenhoveringoverit.This Off
iconsuponhovering allowstoseeallicons.Changingthispreferencedoesnotaffectalreadyopenededitors.
Javaeditorpreferencepage
5.3.1.6.4.MarkOccurrencesPreferences
IndicateyourpreferencesfortheMarkOccurrencessettingsonthe Java>Editor>MarkOccurrencespreferencepage.
Markoccurrencesoftheselectedelementinthecurrentfile Ifenabled,thenyou'llseewithinafile,whereavariable,method,typeorotherelementisreferenced. On
Alistofelementscanbeenabledanddisabledonthispreferencepage.Allareenabledbydefault.
JavaEditorpreferencepage
5.3.1.6.5.JavaSaveActionsPreferences
IndicateyourpreferencesfortheSaveActionssettingsonthe Java>Editor>SaveActionspreferencepage.
AsetofactionswhichareexecutedoneachsaveoftheJavaeditorcanbespecifiedonthispage.
Formatalllines Ifselected,alllinesinthefilewillbeformattedonsave. On
Organizeimports Ifenabled,thentheimportswillbeorganizedoneachsave.ChangetheorganizeimportsettingsontheJava>CodeStyle>Organize On
Importspreferencepage.
Javaeditorpreferencepage
CleanUppreferencepage
5.3.1.6.6.JavaSyntaxColoringPreferences
IndicateyourpreferencesfortheSyntaxColoringsettingsonthe Java>Editor>SyntaxColoringpreferencepage.
SyntaxColoringspecifieshowJavasourcecodeisrendered.Notethatgeneraltexteditorsettingssuchasthebackgroundcolorcanbeconfiguredonthegeneral'TextEditors'
preferencepages.Fontsmaybeconfiguredonthegeneral'ColorsandFonts'preferencepage.
Element
Eachcategory(Java,JavadocandComments)containsalistoflanguageelementsthatmayberenderedwithitsowncolorandstyle. defaultcolorsandstyles
Notethatsomesemantichighlightingoptionscanbedisabledbytheuserinordertoensureeditorperformanceonlowendsystems.
Preview
DisplaysthepreviewofaJavasourcecoderespectingthecurrentcolorsandstyles. n/a
Javaeditor
Javaeditorpreferencepage
5.3.1.6.7.JavaEditorTemplatesPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 180/322
12/10/2015 Javadevelopmentuserguide
The Java>Editor>Templatespreferencepageallowstocreatenewandeditexistingtemplates.Atemplateisaconveniencefortheprogrammertoquicklyinsertoften
reoccurringsourcecodepatterns.
Thefollowingbuttonsallowmanipulationandconfigurationoftemplates:
Action Description
New... OpenstheTemplatedialogtocreateanewtemplate.
Edit... OpenstheTemplatedialogtoeditthecurrentlyselectedtemplate.
Remove Removesallselectedtemplates.
Restore Restoresanypreconfiguredtemplatesthathavebeenremoved.
Removed
Revertto Restoresanypreconfiguredtemplatestotheirdefault.Thisdoesnotmodifyusercreatedtemplates.
Default
Import... Importstemplatesfromthefilesystem.
Export... Exportsallselectedtemplatestothefilesystem.
Usecode Ifenabled,thetemplateisformattedaccordingtothecodeformattingrulesspecifiedintheCodeFormatterpreferences,priortoinsertion.Otherwise,thetemplate
formatter isinsertedasis,butcorrectlyindented.
Templates
Templatevariables
Templateediting
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences
5.3.1.6.7.1.JavaEditorTemplatesPreferences
Thefollowingfieldsandbuttonsappearinthedialog:
Option Description
Name Thenameofthetemplate.
Context Thecontextdetermineswherethetemplatecanbeusedandthesetofavailablepredefinedtemplatevariables.TheJavaeditordefinesacontextforJavaand
Javadocareas.
Javadoc:ProposalisonlyofferedinJavadoccomments
Java:ProposalisonlyofferedinJavacode
Javatypemembers:ProposalisonlyofferedwhencompletingaJavatypemember
Javastatement:ProposalisonlyofferedwhencompletingaJavastatement
SWT:ProposalisonlyofferedwhencompletinginJavacodewithSWTonthebuildpath
SWTtypemembers:ProposalisonlyofferedwhencompletingaJavatypememberwithSWTonthebuildpath
SWTstatement:ProposalisonlyofferedwhencompletingaJavastatementwithSWTonthebuildpath
Automatically Ifselected,codeassistwillautomaticallyinsertthetemplateifitistheonlyproposalavailableatthecaretposition.
insert
Description Adescriptionofthetemplate,whichisdisplayedtotheuserwhenchoosingthetemplate.
Pattern Thetemplatepattern.
InsertVariables... Displaysalistofpredefinedcontextspecifictemplatevariables.
Templates
Templatevariables
Templatespreferences
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences
5.3.1.6.8.JavaEditorTypingPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 181/322
12/10/2015 Javadevelopmentuserguide
Indicateyourpreferencesforthesmartinsertsettingsonthe Java>Editor>Typingpreferencepage.ThosepreferencesareonlyconsideredifSmartInsertModeappearsin
thestatusline.ThiscanbetoggledintheEditmenu.
Enterkeyadjuststheindentationonthenewline Ifenabled,smartindentationwillbeusedtoindentthenewlineafterpressingthe'Enter'key. On
Tabkeyadjuststheindentationofthecurrentline Ifenabledthenthe'Tab'keycanbeusedtoindentthecurrentline. On
Adjustindentation WhenpastingJavacodefromtheclipboardadjustitsindentationtothecurrentindentationlevel. On
Updateimports WhenpastingJavacodefromtheclipboardaddtherequiredimportstatementstotheimportsection. On
Wrapautomatically Ifenabled,stringliteralsarewrappedwhentheyexceedthemaxlinelength. On
Javaeditorpreferencepage
5.3.1.7.InstalledJREsPreferences
Thefollowingpreferencescanbesetusingthe Java>InstalledJREspreferencepage.
ThispageallowsadefaultJREtobeselectedaswellasaddingnewJREinstallations.
Option Description
InstalledJREs ThecurrentlistingofinstalledJREs,allowingyoutoselecttheonetoactastheworkspacedefault
Add... AddsanewJREdefinitiontotheworkbench.
Edit... AllowsyoutoedittheselectedJRE.
Duplicate... CreatesanewJREwiththesameattributesastheselectedJRE.
Remove RemovestheselectedJREfromtheworkbench.
Search... AutomaticallysearchesforJREsinstalledinthelocalfilesystemandcreatescorrespondingJREdefinitionsintheworkspace.
ClasspathVariables
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
AssigningthedefaultJREfortheworkbench
ChoosingaJREforlaunchingaproject
LaunchingaJavaprogram
Runninganddebugging
Usingexternalnullannotations
ExecutionEnvironmentPreferences
JavaDebugPreferences
Run/DebugPreferences
SourceAttachment
5.3.1.7.1.ExecutionEnvironmentsPreferences
Thefollowingpreferencescanbesetusingthe Java>ExecutionEnvironmentspreferencepage.
Thesepreferencesdescribealloftheavailableexecutionenvironments,allowingdefaultJREinstallationstobespecifiedforanygivenenvironment.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 182/322
12/10/2015 Javadevelopmentuserguide
Option Description Default
Execution Thelistingofallavailableexecutionenvironments
environments
Compatible
JREs ThelistingofcompatibleJREinstallationsthatarecompatiblewiththeselectedexecutionenvironment.Youcanselectone(ornone)ofthe
installationstouseasthedefaultfortheselectedexecutionenvironment
AnyJREinstallationsthatperfectlymatchtheexecutionenvironmentaremarkedwithalabel'(perfectmatch)'
Environment Providesadescriptionoftheselectedexecutionenvironment
description
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
InstalledJREsPreferences
JavaDebugPreferences
Run/DebugPreferences
5.3.1.8.JUnitPreferences
The Java>JUnitpreferencepageletsyouconfigurethestacktracefilterpatternsforJUnit.ThepatternsareusedintheJUnitviewtocontrolwhichentriesarevisibleinstack
traces.
Action Description
Enableassertionsfor Ifenabled,thenJUnittestwillbelaunchedwithassertionsenabled.
newJUnitlaunch
configurations
Shownewlylaunched Bydefault,anewJUnittestrunonlyshowsupinthewindowwherethe
testinallJUnitviews testwasstarted.Enablethisoption,ifyouprefertoseethelatesttestinall
openJUnitviews.
AddFilter Allowstoaddacustomfilterpattern.Thisactioninsertsanemptypattern
whichcanbeedited.
AddClass... Allowstoaddclassestobefiltered.ThisactionopenstheOpenType
dialogtochooseatypetobefilteredinthestacktraces.
AddPackages... Allowstoaddpackagestobefiltered.Thisactionopensapackage
selectiondialogtochoosethepackagestobefilteredinthestacktraces.
Remove Removesthecurrentlyselectedstacktracefilterpattern.
EnableAll Enablesallstacktracefilterpatterns.
DisableAll Disablesallstacktracefilterpatterns.
UsingJUnit
Opentype
5.3.1.9.PropertiesFilesEditorPreferences
IndicateyourpreferencesforthePropertiesFilesEditorsettingsonthe Java>PropertiesFilesEditorpreferencepage.
Syntaxcoloringspecifieshowthecontentof'.properties'filesrendered.Notethatgeneraltexteditorsettingssuchasthebackgroundcolorcanbeconfiguredonthegeneral'Text
Editors'preferencepages.
Element
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 183/322
12/10/2015 Javadevelopmentuserguide
Alistofelementsthatmayberenderedwithitsownforegroundcolorandstyle. defaultcolorsandstyles
Preview
Displaysthepreviewofapropertiesfilerespectingthecurrentcolorsandstyles. n/a
5.3.2.DebugPreferences
Thefollowingpreferencescanbesetusingthe Run/Debugpreferencepage.
Thepreferencesherearegenerictoalldebuggers,andgovernstylisticandpromptingoptions
Reuseeditorwhen Thedebuggerdisplayssourcecodeinaneditorwhensteppingthroughanapplication.Whenthisoptionison,thedebuggerwillreusetheeditor On
displayingsource thatitopenedtodisplaysourcefromdifferentsourcefiles.Thispreventsthedebuggerfromopeninganexcessivenumberofeditors.Whenthis
code optionisoff,thedebuggerwillopenaneweditorforeachsourcefilethatneedstobedisplayed.
Activatethe Thisoptionbringsattentiontothedebuggerwhenabreakpointisencountered,byactivatingtheassociatedwindow.Thevisualresultvariesfrom On
workbenchwhena platformtoplatform.Forexample,onWindows,theassociatedwindow'stitlebarwillflash.
breakpointishit
Activatethedebug Thisoptionbringsattentiontothedebugviewwhenabreakpointisencountered.Iftheviewisalreadyopenitwillbeactivated.Iftheviewisnot On
viewwhena alreadyopenitwillbeopenedautomatically.
breakpointishit
Skipbreakpoints Thisoptioncontrolswhetherbreakpointsareignoredwhenperforminga'RuntoLine'operation.Whentheoptionison,thedebuggerdoesnot Off
duringa'RuntoLine' suspendatbreakpointsencounteredwhena'RuntoLine'operationisinvoked.Whentheoptionisoff,breakpointsbehavenormally.
operation
Promptfor Thisoptioncontrolswhetheryouwillbepromptedforconfirmationwhenyoutrytodeleteallofyourbreakpoints On
conformationwhen
deletingall
breakpoints
Promptfor Thisoptioncontrolsifyouwillbepromptedforconfirmationwhenyoutrytodeleteabreakpointcontainer,e.g.abreakpointworkingset On
confirmationwhen
deletingbreakpoint
containers
Changedvaluecolor Thisoptionallowsyoutochangethecolorofachangedvalueinthevariablesview,expressionsview,memoryview,anywhererunningprogram Red
variablesarerendered
Changedvalue Thisoptionallowsyoutochangetheselectioncolorofachangedvariable,e.g.inthevariablesviewshowingcolumns Yellow
backgroundcolor
Memoryunbuffered Thisoptionallowsyoutochangetherenderingcolorofunbufferedmemoryblocksinthememoryview Grey
color
Memorybuffered Thisoptionallowsyoutochangetherenderingcolorofbufferedmemoryblocksinthememoryview Black
color
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
StringSubstitutionPreferences
ViewManagementPreferences
5.3.2.1.ConsolePreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Consolepreferencepage.
Theconsoledisplaysoutputfromrunningapplications,andallowskeyboardinputtobereadbyrunningapplications.
Limitconsoleoutput Thispreferencelimitsthenumberofcharactersbufferedintheconsole.Whenon,amaximumbuffersizemustalsobespecified.Whenconsole On
outputsurpassesthespecifiedmaximum,outputistruncatedfromthebeginningofthebuffer.
DisplayedTab Allowsthedefaultwidth,incharacters,ofatabtobespecified 8
Width
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 184/322
12/10/2015 Javadevelopmentuserguide
ShowWhen Thispreferencewillforcetheconsoletoshowwhensomethingiswrittentothesystemoutstream.Aforcedshowcanmeanthataconsolewillbe On
ProgramWritesto opened,orthattheconsolewillbebroughttothetopifitisalreadyopen.
StandardOut
ShowWhen Thispreferencewillforcetheconsoletoshowwhensomethingiswrittentothesystemerrstream.Aforcedshowcanmeanthataconsolewillbe On
ProgramWritesto opened,orthattheconsolewillbebroughttothetopifitisalreadyopen.
StandardError
YoucanalsoclicktheChangebuttontosetthefontfortheConsole.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
ConsoleView
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences
5.3.2.2.LaunchingPreferences
Thesepreferencesallowyoutoconfigureoptionsrelatedtolaunchingprogramsingeneral,andgovernsuchthingsaswaitingforbuilds,savingfilesbeforelaunching,etc.
Thefollowingpreferencescanbesetusingthe Run/Debug>Launchingpreferencepage.
Saverequireddirtyeditorsbefore Prompt
launching Thisoptioncontrolswhethertheuserwillbepromptedtosaveanydirtyeditorsbeforeanapplicationislaunched.The
allowablesettingsare:
Alwayswhenthisoptionisselected,theuserisneverpromptedtosavedirtyeditors,andeditorsare
automaticallysaved.
Neverwhenthisoptionisselected,theuserisneverpromptedtosavedirtyeditors,andeditorsarenot
automaticallysaved.
Promptwhenthisoptionisselected,theuserispromptedtosavedirtyeditorsbeforelaunchinganapplication.
Waitforongoingbuildtocomplete Always
beforelaunching Thisoptioncontrolswhetheralaunchwillwaitforanalreadyexecutingbuildtocompletebeforelaunchinganapplication.
Theallowablesettingsare:
Alwayswhenthisoptionisselected,alaunchwillalwayswaitforthependingbuildtocomplete
Neverwhenthisoptionisselected,alaunchwillneverwaitforthependingbuildtocomplete
Promptwhenthisoptionisselected,theuserispromptedtowaitforthependingbuildtocompletewhenthey
launch
Launchindebugmodewhenever Never
theworkspacecontainsbreakpoints Thisoptioncontrolswhetheralaunchwillbeperformedindebugmode,evenwhenrunispressed,whentheworkspace
containsbreakpoints.Theallowableoptionsare:
Alwayswhenthisoptionisselected,alaunchwillalwaysbeperformedindebugmodewhenbreakpointsare
present,nomatterwhichlaunchbuttonispressed(runordebug)
Neverwhenthisoptionisselected,alaunchwillalwaysbeperformedintheuserspecifiedmode
Promptwhenthisoptionisselected,theuserispromptedtolaunchindebugmodewhentheworkspacecontains
breakpoints
Continuelaunchifprojectcontains Prompt
errors Thisoptioncontrolswhetheralaunchshouldbeperformedwhenarelatedprojectcontainsanerror.Theallowable
optionsare:
Alwayswhenthisoptionisselected,alaunchwillcontinueinthefaceofcompilationerrors
Promptwhenthisoptionisselected,theuserispromptedtoproceedwithalaunchwhenrelevantcompilation
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 185/322
12/10/2015 Javadevelopmentuserguide
errorsareinanassociatedproject
Build(ifrequired)beforelaunching Iftheworkspacerequiresbuilding,anincrementalbuildwillbeperformedpriortolaunchinganapplication. On
Removeterminatedlauncheswhen Whenanapplicationislaunched,allterminatedapplicationsintheDebugviewareautomaticallycleared. On
anewlaunchiscreated
Sizeofrecentlylaunched ThisoptioncontrolshowmanylauncheswillappearintheRun/Debugpulldownlaunchhistorymenus. 10
applicationslist
LaunchOperation LaunchSelected
Newin3.3istheabilitytolaunchtheselectedresourceoreditor.Thelaunchoperationpreferenceallowsuserstoswitch withLaunch
betweenusingtheold'alwayslaunchlast'behaviorandthenew'launchselectedresourceoreditor'behavior. Project
Ifthepreferencetouselaunchselectedresourceoreditorisselected,youcanthencustomizewhathappensifthe
selectedresourceoreditorisnotlaunchable.
Therearetwochoicesforthis
1. trytolaunchtheparentprojectoftheresourceoreditor
2. launchthepreviousthingyoulaunched.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
RunandDebugtoolbaractions
ConsolePreferences
DefaultLaunchersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchConfigurationsPreferences
PerspectivesPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences
5.3.2.2.1.DefaultLaunchersPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Launching>DefaultLauncherspreferencepage.
TheDefaultLauncherspreferenceallowsyoutoselectwhatlaunchtoolingistobeusedifmorethanonekindoftoolingexistsforthesamething,forexample,considerusingtwo
profilersatthesametimeforJavaprograms.Forthemostpart,thispageremainsdisabled,asconcurrentoverlappingtoolingisveryrare,butintheeventthereisoverlap,thepage
willenableandpresenttheuserwiththelaunchtypesthatconflictandwhatmodestheyconflicton.
ThefollowingimageshowsthepagewithconflictingtoolingforJavatypesintherun,debugandAlternate2modes.Inthisexampleapreferredlaunchercanbeselected
independentlyforeachoftheconflictingmodes.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 186/322
12/10/2015 Javadevelopmentuserguide
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
InstalledJREsPreferences
JavaDebugPreferences
LaunchConfigurationsPreferences
LaunchingPreferences
Run/DebugPreferences
5.3.2.2.2.LaunchConfigurationsPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Launching>LaunchConfigurationspreferencepage.
Thispageallowsyousetfilteringoptionsthatareusedthroughouttheworkbenchtolimittheexposureofcertainkindsoflaunchconfigurations.Thesefilteringsettingaffectthe
launchdialog,launchhistoriesandtheworkbench.
Filterconfigurationsin Filteroutconfigurationsthatareassociatedwithaprojectthatiscurrentlyclosed On
closedprojects
Filtersconfigurationin Filteroutconfigurationsthatareassociatedwithaprojectthathasbeendeletedoraresimplynolongeravailable(notintheworkspace,etc) On
deletedormissing
projects
Applywindowsworking Appliesthefilteringfromanyworkingsetscurrentlyactivetothevisibilityofconfigurationsassociatedtoresourcesintheactiveworkingsets. On
set i.e.ifprojectPhastwoconfigurationsassociatedwithit,butisnotinthecurrentlyactiveworkingset,theconfigurationsdonotappearinthe
UI,muchlikePdoesnot.
Filtercheckconfiguration Filterallconfigurationsoftheselectedtyperegardlessoftheotherfilteringoptions.ForexampleifyouspecifytofilterJavatype Off
types configurations,allJavatypeconfigurationswillbefilteredfromtheUI,notjustonesthatfallundertheotherfilteringcategories.
Deleteconfigurations Anylaunchconfigurationsassociatedwithaprojectbeingdeletedwillalsobedeletedifthisoptionisenabled.Oncedeletedtheconfigurations On
whenassociatedproject arenotrecoverable.
isdeleted
Migration
AsEclipsematuresandnewfeaturesareaddedtothelaunchingframework,theresometimesexiststheneedtomakechangestolaunch
configurations.Someofthesechangesaremadeautomatically,butthosethatarenot(nonreversibleones)areleftuptotheenduser.
Themigrationsectionallowsuserstoselfmigrateanylaunchconfigurationsthatrequireit.UponpressingtheMigrate...button,ifthereare
anyconfigurationsrequiringmigration,theyarepresentedtotheuser,andtheusercanselecttheonestheywanttomigrate.Configuration
migrationisnotundoable.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
DefaultLaunchersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
Run/DebugPreferences
5.3.2.3.PerspectivesPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Perspectivespreferencepage.
Thepreferencesonthispageallowyoutosetwhich,ifanyperspectivesareautomaticallyopenedwhenlaunchersareusedincertainmodes
Opentheassociatedperspective Never
whenlaunching Thisoptioncontrolsifthespecifiedperspectivewillbeswitchedtoautomaticallyornotwhenlaunching
Alwaysthespecifiedperspectivewillalwaysbeopened
Neverthespecifiedperspectivewillneverbeopened
Prompttheuserwillbepromptedtoswitchtothespecifiedperspective
Opentheassociatedperspective Prompt
Thisoptioncontrolsifthespecifiedperspectivewillbeswitchedtowhentheapplicationsuspends
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 187/322
12/10/2015 Javadevelopmentuserguide
whenanapplicationsuspends Alwaysthespecifiedperspectivewillalwaysbeopened
Neverthespecifiedperspectivewillneverbeopened
Prompttheuserwillbepromptedtoswitchtothespecifiedperspective
Launcher/Perspectivechoices Thisoptionareaallowsyoutocustomizewhatperspectivewillbeopenedforagivenlaunchandmodethatitsupports.Forexample,
youcansaythatyouwanttoopentheJavaperspectivewhenusingtheJavaJDTlauncherintherunmodeonly.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences
5.3.2.4.StringSubstitutionPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>StringSubstitutionpreferencepage.
Thispreferencepageisusedsolelyforthepurposeofcreatingstringvariablestobereusedinotherlocationsthatacceptstringvariablesubstitution.
TheplatformSDKforEclipseusesstringvariablesinthelaunchdialogforsettingprogramandVMargumentsforcertaintypesoflaunchconfigurations,aswellasallowing
substitutionsforAnttargetsintheExternalToolslaunchdialog.ConsiderthefollowingscreenshotwhichshowstheStringSubstitutionpreferencepagewithanewTESTstring
variablecreated.
InthiscasetheTESTvariabledoesnothing,butinthe'real'worlditcouldpointtoadirectoryorprogramthatyouwouldliketoreusethepathforinconfigurations,etc.
Ifwenowwanttoleveragethisnewvariable,wecandosofromthelaunchdialogontheargumentstab(forthoseconfigurationsthathaveastandardargumentstab),byselecting
theVariables...buttonforeithertheprogramorVMargumentstextarea.SelectingtheVariablesbuttonopensadialogwithalistingofallofthestringvariablesavailable.
InthefollowingscreenshotwecanseetheTESTvariableavailableinthelist.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 188/322
12/10/2015 Javadevelopmentuserguide
WecannowselecttheTESTvariableandinsertinasanargumentifwewish,asshowninthefollowingscreenshot.
TheothermentionedplatformuseofstringsubstitutionintheExternalToolslaunchdialog,usedwithAntconfigurations,asshowninthefollowingscreenshot.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 189/322
12/10/2015 Javadevelopmentuserguide
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
Run/DebugPreferences
ViewManagementPreferences
5.3.2.5.ViewManagementPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>ViewManagementpreferencepage.
Thesepreferencesallowyoutoconfigurewhichviewswillactivelysupportautomaticviewopening.
Perspectives Thelistingofperspectivestoselectwhichoneswillsupportautomaticviewopening
Donotautomaticallyopen/closeviewswhichhavebeenmanually Thisoptioncontrolsifviewsmanuallyopened/closedwillbeaffectedbyview On
opened/closed management
Resetbutton Resetsthelistingofsupportingperspectives.
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging
LaunchingaJavaprogram
Runninganddebugging
ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 190/322
12/10/2015 Javadevelopmentuserguide
Run/DebugPreferences
StringSubstitutionPreferences
5.4.1.JavadocLocationDialog
ThisdialogletsyoudefinethelocationoftheJavadocdocumentationforaJARoraJavaproject.
Youcanreachthisdialogthefollowingways:
SelectaJARorJavaproject,openthecontextmenuandselectProperties>JavadocLocationorusePropertiesfromtheFilemenu
IntheJavadocgenerationwizard,ontheStandarddocletsettingspage,chooseConfigure
JavadoccanbeattachedtoJARs,classfoldersorJavaprojects.Forprojectsitdocumentstheelementsofallsourcefolders,forJARsandclassfolders,elementscontainedinthe
JARaredocumented.Thelocationisusedby
OpenAttachedJavadocintheNavigatemenutoopentheattachedJavadocofanelement
ContextHelp(F1)topointtoaJavadoclocation
JavadocExportWizardtolinktootherdocumentationorasdefaultdestinationforaproject'sdocumentation
ValidlocationsareURLsthatpointtoafoldercontainingtheAPIdocumentation'sindex.htmlandpackagelistfile.Examplesare:
file:///M:/JAVA/JDK1.2/DOCS/API/
http://download.oracle.com/javase/6/docs/api/
<empty>
Javadoc SpecifythelocationofthegeneratedJavadocdocumentation.YoucanBrowseinthelocalfilesystemforaJavadoclocation(willresultinafile://URL)
URL
Validate Validatethecurrentlocationbytryingtoaccesstheindex.htmlandpackagelistfilewiththegivenURL.Ifthevalidationwassuccessful,youcandirectly
openthedocumentation.
JavadocforJARsandclassfolderscanalsobelocatedinsideanarchiveavailableonthelocalfilesystem.Inthatcasethelocationofthearchiveaswellasthelocationofthedoc
insidethearchivehastobespecified.
<empty>
Archive SpecifythelocationofthearchivethatcontainsthegeneratedJavadocdocumentation.YoucanBrowseinthelocalfilesystemforaJavadoclocation
location
<empty>
Pathwithin SpecifythepathinsidethearchivethatcontainsthegeneratedJavadocdocumentation.YoucanBrowsetoseethecontentofthearchive.
archive
Validate Validatethecurrentlocationbytryingtoaccesstheindex.htmlandpackagelistfilewiththegivenURL.Ifthevalidationwassuccessful,youcan
directlyopenthedocumentation.
5.4.2.JavaBuildPath
TheoptionsinthispageindicatethebuildpathsettingsforaJavaproject.Youcanreachthispagethroughtheprojectproperties(Project>Properties>JavaBuildPath)fromthe
contextmenuonacreatedprojectortheFilemenuoftheworkbench.
Thebuildclasspathisalistofpathsvisibletothecompilerwhenbuildingtheproject.
Sourcetab
Sourcefoldersaretoplevelfoldersintheprojecthierarchy.Theyaretherootofpackagescontaining.javafiles.Thecompilerwilltranslatethecontainedfilesto.classfilesthatwill
bewrittentotheoutputfolder.
Sourcefoldersallowtostructuretheproject,forexampletoseparatetestfromtheapplicationintwosourcefolders.Withinasourcefolder,amoredetailedstructuringcanbe
achievedbyusingpackages.
Eachsourcefoldercandefineanexclusionfiltertospecifywhichresourcesinsidethefoldershouldnotbevisibletothecompiler.
ResourcesexistinginsourcefoldersarecopiedtotheoutputfolderunlessthesettingintheJava>Compiler>Buildingpreferencepagespecifiesthattheresourceisfiltered.The
outputfolderisdefinedperprojectexceptifasourcefolderspecifiesitsownoutputfolder.
Sourcefolderoptions:
Option Description
AddFolder Createsanewfoldertocontainsource
LinkSource Createsanewfolderthatlinkstoanlocationoutsideoftheworkspace
Edit Allowstomodifythecurrentlyselectedsourcefolderorsourcefolderattribute.
Removestheselectedfoldersfromtheclasspath.Thisdoesnotdeletethe
Remove
foldersnortheircontents.
Allowoutputfolder
Shows/Hidesthe'outputfolder'attributeofthesourcefolders
persourcefolder
Sourcefolderattributes:
Attribute Description
Exclusionfilter Selectswhichresourcesarenotvisibletothecompiler.FordetailsseeInclusion
andexclusionpatterns.
Outputfolder OnlyavailablewhenAllowoutputfolderpersourcefolderischecked.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 191/322
12/10/2015 Javadevelopmentuserguide
Definesasourcefolderspecificoutputlocation.Ifnotsettheproject'sdefault
outputfolderisused.
Nativelibrary Definesthefolderthatcontainsthenativelibraries(forexample'dll'or'o'files)
location requiredatruntimebythesourcesinthesourcefolder.
Atthebottomofthispage,theDefaultoutputfolderfieldallowsyoutoenterapathtoafolderpathwherethecompilationoutputforthisprojectwillreside.Thedefaultoutputis
usedforsourcefoldersthatdonotspecifyanownoutputfolder.UseBrowsetoselectanexistinglocationfromthecurrentproject.
Projectstab
IntheRequiredprojectsonthebuildpathlist,youcanaddprojectdependenciesbyselectingotherworkbenchprojectstoaddtothebuildpathforthisnewproject.
Addingarequiredprojectindirectlyaddsallitsclasspathentriesmarkedas'exported'.SettingaclasspathentryasexportedisdoneintheOrderandExporttab.
Theprojectsselectedhereareautomaticallyaddedtothereferencedprojectslist.Thereferencedprojectlistisusedtodeterminethebuildorder.Aprojectisalwaysbuildafterallits
referencedprojectsarebuilt.
Action Description
Add Addanotherprojectintheworkspacetothebuildpathofthisproject.
Edit Edittheclasspathattributeofarequiredproject.
Remove Removestheselectedrequiredprojectsfromthelist.
Projectentryattributes:
Attribute Description
Nativelibrary Specifieswherenativelibraryrequiredfortheprojecttooperatecanbefound.
location
Accessrules Specifiesaccessrulesforprojectcontainedinthelibrary.Thisallowstohide
contentofaproject.
Librariestab
Onthispage,youcanaddlibrariestothebuildpath.
Bydefault,thelibrarylistcontainsanentryrepresentingtheJavaruntimelibrary.ThisentrypointstotheJREselectedasthedefaultJRE.ThedefaultJREisconfiguredintheJava
>Debug>InstalledJREspreferencespage.
Librariestaboptions:
Option Description
AddJARs AllowsyoutonavigatetheworkbenchhierarchyandselectJARfilestoaddto
thebuildpath.
AddExternal Allowsyoutonavigatethefilesystem(outsidetheworkbench)andselectJAR
JARs filestoaddtothebuildpath.
AddVariable Allowsyoutoaddclasspathvariablestothebuildpath.Classpathvariablesare
anindirectiontoJARswiththebenefitofavoidinglocalfilesystempathsina
classpath.Thisisneededwhenprojectsaresharedinateam.
VariablescanbecreatedandeditedintheJava>BuildPath>Classpath
Variablespreferencepage.
AllowstoaddapredefinedlibrariesliketheJRESystemLibrary.Suchlibraries
AddLibrary canstandforanarbitrarynumberofentries(visibleaschildrennodeofthe
librarynode)
Allowstonavigatetheworkbenchhierarchyandselectaclassfolderforthe
AddClassFolder
buildpath.Theselectiondialogalsoallowsyoutocreateanewfolder.
Allowstonavigatethefilesystem(outsidetheworkbench)andselectaclass
AddExternal
folderforthebuildpath.Theselectiondialogalsoallowsyoutocreateanew
ClassFolder
folder.
Edit Allowsyoutomodifythecurrentlyselectedlibraryentryorentryattribute
Remove Removestheselectedelementfromthebuildpath.Thisdoesnotdeletethe
resource.
MigrateJARFile MigrateaJARonthebuildpathtoanewerversion.Ifthenewerversion
containsrefactoringscriptstherefactoringstoredinthescriptwillbeexecuted.
Librarieshavethefollowingattributes(presentedaslibraryentrychildrennodes):
Libraryentryattributes:
Attribute Description
Source Specifieswherethelibrary'ssourcecanbefound.
attachment
Javadoclocation Specifieswherethelibrary'sJavadocdocumentationcanbefound.Ifspecified
youcanuseShift+F2onanelementofthislibrarytoopenitsdocumentation.
External Specifieswhereexternalannotationsforthelibrarycanbefound.Ifspecified
annotations theseannotationswillbeconsideredbyJDTforitsstaticnullanalysis.
Nativelibrary Specifieswherenativelibraryrequiredforthelibrarytooperatecanbefound.
location
Accessrules Specifiesaccessrulesforresourcescontainedinthelibrary.Thisallowstohide
contentofalibrary.
OrderandExporttab
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 192/322
12/10/2015 Javadevelopmentuserguide
IntheBuildclasspathorderlist,youcanclicktheUpandDownbuttonstomovetheselectedpathentryupordowninthebuildpathorderforthisnewproject.
Checkedlistentriesaremarkedasexported.Exportedentriesarevisibletoprojectsthatrequiretheproject.UsetheSelectAllandDeselectAlltochangethecheckedstateofall
entries.Sourcefoldersarealwaysexported,andcannotbedeselected.
Buildclasspath
Classpathvariables
Inclusionandexclusionpatterns
FrequentlyaskedquestionsonJDT
Classpathvariablespreferences
Buildpathpreferences
Compilerpreferences
5.4.3.JavaCompilerPage
TheoptionsinthispageindicatethecompilersettingsforaJavaproject.
Youcanreachthispagethroughthe
JavaCompilerpropertypage(File>Properties>JavaCompiler)fromthecontextmenuonacreatedprojectortheFilemenu
Aprojectcaneitherreuseworkspacedefaultsettingsoruseitsowncustomsettings.
Option Description
Enableproject Onceselected,compilersettingscanbeconfiguredforthisproject.AllJavacompilerpreferencescanbecustomized.Atanytime,itispossibletorevertto
specificsettings workspacedefaults,byusingthebuttonRestoreDefaults.
Buildclasspath
Javacompilerpreferences
JavaBuildPathproperties
FrequentlyaskedquestionsonJDT
5.4.4.JavaTaskTagsPage
TheoptionsinthispageindicatethetasktagsforaJavaproject.
Youcanreachthispagethroughthe
Javatasktagspropertypage(File>Properties>JavaCompiler>TaskTags)fromthecontextmenuonacreatedprojectortheFilemenu
Aprojectcaneitherreuseworkspacedefaultsettingsoruseitsowncustomsettings.
Option Description
Enableprojectspecific Onceselected,tasktagscanbeconfiguredforthisprojectasintheTasktagspreferencepage.Atanytime,itispossibletoreverttoworkspace
settings defaults,byusingthebuttonRestoreDefaults.
Tasktagpreferences
5.4.5.SourceAttachmentPropertyPage
Tobrowsethesourceofatypecontainedinlibraryyoucanattachasourcearchiveorsourcefoldertothislibrary.Theeditorwillthenshowthesourceinsteadofthedecompiled
code.Settingthesourceattachmentalsoallowssourcelevelsteppingwiththedebugger.
TheSourceAttachmentdialogcanbereachedinseveralways:
SelectaJARinthePackageExplorerandchooseProperties>JavaSourceAttachmentfromthecontextmenuortheProjectmenu
OpentheJavaBuildPathpageofaproject(Projects>Properties>JavaBuildPath).OntheLibrariespageexpandthelibrary'snodeandselecttheSourceattachment
attributeandpressEdit
Openaneditoronaclassfile.IfthesourceattachmenthasnotalreadybeenconfiguredforthisJAR,theeditorcontainsabuttonAttachSource
DependingofhowaJARwascontributedtotheclasspath,youcanseedifferenttypesofSourceattachmentdialogs:
JAR
InthePathfield,enterthepathofanarchiveorafoldercontainingthesource.UseeithertheWorkspace,ExternalFileortheExternalFolderbuttontobrowseforalocation.
ForasourceattachmentinanexternallocationyoucanalsospecifyanoptionalEncodingforreadingthesourceattachment.Bydefaulttheworkspaceencodingisused.
Variable
IntheLocationVariablePathfieldenteravariablepaththatpointstothesourceattachment'slocation.Avariablepathhasasfirstsegmentavariable(whichwillresolvetoafolder
orfile),therestisanoptionalpathextension(e.g.MYVARIABLE/src.jar).UseeithertheVariablebuttontoselectanexistingvariableandtheExtensionbuttontoselectthe
extensionpath.TheExtensionbuttonisonlyenabledwhenthevariablecanbeextended(resolvestoafolder)
JRE_SRCisareservedvariablethatpointstoaJREselectedintheInstalledJREspreferencepage( Java>InstalledJREs).Gotothispreferencepagetoconfigurethesource
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 193/322
12/10/2015 Javadevelopmentuserguide
attachmentfortheJRE'slibrary..
Buildclasspath
InstalledJREspreferences
Javabuildpathproperties
5.4.6.Run/DebugPropertiesPage
Thispropertypageallowsyoutoviewandmanagealllaunchconfigurationsthatapplytothepages'correspondingresource.
Option Description
Launch Thelistshowsallofthelaunchconfigurationsinthecurrentworkspacethatapplytothepropertypages'correspondingresource.
Configuration
List
New... TheNew...buttoncanbeusedtocreateanewlaunchconfigurationthatappliestothecorrespondingresource.Whenselected,theNew...buttonwillpresentyou
withadialogofallofthelaunchconfigurationtypesthatcanbeusedtomakeaconfigurationthatappliestothecorrespondingresource.
Duplicate TheDuplicatebuttonisusedtomakeanidenticalcopyofaselectedlaunchconfiguration.
Edit... TheEdit...buttonwillopenthelaunchconfigurationeditdialog,allowingyoutochangetheselectedlaunchconfiguration.
Delete TheDeletebuttonisusedtodeletetheselectedlaunchconfiguration.
LocalDebugging
RemoteDebugging
LaunchingaJavaProgram
LaunchingaJavaprogramindebugmode
PreparingtoDebug
Relaunchingaprogram
LaunchingaJavaapplet
DisconnectingfromaVM
UsingtheremoteJavaapplicationlaunchconfiguration
RunandDebugtoolbaractions
5.5.2.RefactoringWizard
Adialogbaseduserinterfaceguidesyouthroughthestepsnecessarytoexecuteaselectedrefactoring.Dependingonthecomplexityoftherefactoring,eitherawizardorasimple
dialogisusedtogatherinformationthatisrequiredfortherefactoring.
Inputpages
Theinputpagesgatherinformationthatisrequiredfortherefactoring.AfteryouhaveprovidedtherequiredinputyoucanclickOkorFinishtocarryouttherefactoringwithout
previewingtheresults.IfyouwanttopreviewthechangespressPrevieworNext
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 194/322
12/10/2015 Javadevelopmentuserguide
Previewpage
TheJDTallowsyoutopreviewtheresultsofarefactoringactionbeforeyouexecuteit.
Thepreviewpageconsistsoftwoparts:
AtreeatthetopcontainingallJavaelementsaffectedbytherefactoring.Eachtoplevelnodeinthetreerepresentsonecompilationunit.
Somerefactoringsallowtofilterthetreebydifferentkindofchangesmadebytherefactoring.UsetheFilterChangesdropdowntochangethefiltering.
Acomparevieweratthebottom.Theleftsideofthecompareviewershowstheoriginal,therightsidedisplaystherefactoredsource.
Problempage
TheRefactoringProblempageindicatesiftherearesuspected,potential,ordefiniteproblemswiththerefactoringactionyouareattempting.
Fourtypesofproblemsarepossible:
Information
AproblemdescribedasInformationwillnotaffecttherefactoringinanyway,norwillitnegativelyaffectthecodeintheworkbench.Youcanmostlikelyignorethistypeof
problem.
Warnings
Warningsattempttopredictcompilewarnings.Thistypeofproblemmostlikelywillnotnegativelyaffectthecodeinyourworkbench.
Errors
AproblemdescribedasanErrorisverylikelytocausecompileerrorsorchangeyourworkbenchcodesemantically.Youcanchoosetocontinuewiththerefactoringinspiteof
theseerrors,althoughitisnotrecommended.
Stopproblems
Thistypeofproblempreventstherefactoringfromtakingplace.Forexample,ifyouselectacommentandchoosetheExtractMethodcommandfromit,theworkbenchwill
issueastopproblemontherefactoringattemptbecauseyoucannotextractacomment.
Iftherearen'tanystopproblemsthentherefactoringcanbecarriedoutbypressingtheFinishbutton.Topreviewtheresultsoftherefactoringaction,presstheNext>button.
RefactoringwithoutDialog
ItisalsopossibletorenameaJavaelementwithoutshowingadialog.ThiscanbeenabledanddisabledontheJavapreferencepage.Ifenabled,thenthenewnameforanJava
elementcanbetypedintotheeditorwhentherenamerefactoringisinvoked.
Refactoringsupport
Refactoringactions
Icons
5.5.3.ExtractMethodErrors
Whenyouattempttoextractamethod,youmaygetoneormoreofthefollowingcommonerrors:
SelectedblockreferencesalocaltypedeclaredoutsidetheselectionAlocaltypedeclarationisnotpartoftheselectionbutisreferencedbyoneofthe
statementsselectedforextraction.Eitherextendtheselectionthatitincludesthelocaltypedeclarationorreducetheselectionthatnoreferencetothelocaltypedeclarationis
selected.
AlocaltypedeclaredintheselectedblockisreferencedoutsidetheselectionTheselectioncoversalocaltypedeclarationbutthetypeisalsoreferenced
outsidetheselectedstatements.Eitherextendtheselectionthatisincludesallreferencestothelocaltypeorreducetheselectionthatthelocaltypedeclarationisn'tselected.
Ambiguousreturnvalue:selectedblockcontainsmorethanoneassignmenttolocalvariableMorethanoneassignmenttoalocalvariablewasfoundinsidethe
selectedblock.Eitherreducetheselectionthatonlyoneassignmentisselectedorextendtheselectionthatatleastallreferenceexceptofonetothelocalvariablesare
coveredbytheselectiontoo.
Ambiguousreturnvalue:expressionaccesstolocalandreturnstatementselectedTheselectedstatementgeneratesmorethanonereturnvalue.Thisisfor
examplethecaseifanexpressionisselectedandanexpression'sargumentismodifiedaswell.Toremedythisproblemextendtheselectiontocoverthereadaccessofthe
modifiedargumentaswell.
Selectioncontainsabreakstatementbutthecorrespondingbreaktargetisn'tselectedToremedytheproblemeitherextendtheselectiontoincludethebreak/
continuetargetorreducetheselectionthatthebreak/continuestatementisn'tcoveredbytheselection.
Selectioncontainsacontinuestatementbutthecorrespondingcontinuetargetisn'tselectedToremedytheproblemeitherextendtheselectiontoincludethe
break/continuetargetorreducetheselectionthatthebreak/continuestatementisn'tcoveredbytheselection.
SelectionstartsinsideacommentPartsofacommentcannotbeextracted.Eitherextendtheselectionthatitcoversthewholecommentorreducetheselectionthatthe
commentisn'tcoveredatall.
SelectionendsinsideacommentPartsofacommentcan'tbeextracted.Eitherextendtheselectionthatitcoversthewholecommentorreducetheselectionthatthe
commentisn'tcoveredatall.
CannotextractselectionthatendsinthemiddleofastatementAdjustselectionsothatitfullycoversasetofstatementsorexpressions.Theuserscanextend
theselectiontoavalidrangeusingtheExpandSelectiontointheEditmenu.
Javadevelopmenttools(JDT)
Refactoringsupport
Sourcemenu
Refactormenu
5.6.1.JavaSearchTab
ThistabintheSearchdialogallowsyoutosearchforJavaelements.ToshowthetabinvokeSearch>Java.
Searchstring
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 195/322
12/10/2015 Javadevelopmentuserguide
Inthisfield,typetheexpressionforwhichyouwishtosearch,usingthewildcardcharactersmentionedinthedialogasneeded.Thisfieldisinitializedbasedonthecurrentselection.
Typepatternshavethefollowingsyntax:
[qualification'.']typeName['<'typeArguments'>']
Examples:
java.lang.Object
Runnable
List<String>
Typeargumentscanbespecifiedtosearchforreferencestoparameterizedtypesusingfollowingsyntax:
'<'{['?'{'extends'|'super'}]type(','['?'{'extends'|'super'}]type)*|'?'}'>'
Notethat:
'*'isnotvalidinsidetypeargumentsdefinition<>
'?'istreatedasawildcardwhenitisinside<>(i.e.itmustbeputonfirstpositionofthetypeargument)
Methodpatternshavethefollowingsyntax:
[declaringType'.']['<'typeArguments'>']methodName['('parameterTypes')'][returnType]
Typeargumentshavethesamesyntaxasexplainedinthetypepatternssection.
Examples:
java.lang.Runnable.run()void
main(*)
<String>toArray(String[])
Constructorpatternshavethefollowingsyntax:
['<'typeArguments'>'][declaringQualification'.']typeName['('parameterTypes')']
Typeargumentshavethesamesyntaxasexplainedinthetypepatternssection.
Notethattheconstructornameshouldnotbeenteredasitisalwaysthesameasthetypename.
Examples:
java.lang.Object()
Test(*)
<Exception>Sample(Exception)
Fieldpatternshavethefollowingsyntax:
[declaringType'.']fieldName[fieldType]
Examples:
java.lang.String.serialVersionUIDlong
field*
Packagepatternshavethefollowingsyntax:
packageNameSegment{'.'packageNameSegment}
Examples:
java.lang
org.e*.jdt.c*e
SearchFor
Selecttosearchforoneofthefollowingkindsofelements:
Type
Method
Package
Constructor
Field
LimitTo
Selecttolimityoursearchresultstooneofthefollowingkindsofmatches:
Declarations
Implementors(availableonlywhensearchingfortypes)
References
Alloccurrences
Readaccess(availableonlywhensearchingforfields)
Writeaccess(availableonlywhensearchingforfields)
Matchlocations(availableonlywhensearchingfortypesormethodsreferences).
Matchlocationsallowtofurthernarrowthelocationofmatches.
Selectthelocationwheretosearchfor:
typereference:
Superclassdeclarations
Annotations
Fieldtypes
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 196/322
12/10/2015 Javadevelopmentuserguide
Localvariabletypes
Methodreturntypes
Methodparametertypes
Thrownexceptiontypes
Typeparameterbounds
Wildcardbounds
Typeargument
Castexpressions
Catchclauses
Classinstancecreations
'instanceof'checks
methodreference:
'this.'references
Implicit'this.'references
'super.'references
Qualifiedreferences
'::'methodreferences
SearchIn
Selectwhereinthescopetosearchforresults
Sources:Searchinallsourcefilesinthescope
Requiredprojects:Searchinallrequiredprojects
JRElibraries:SearchinJRElibrariesonthebuildpath
Applicationlibraries:Searchinlibrariesonthebuildpath
Scope
Selecttolimityoursearchresultstooneofthefollowingscope
Workspace
Selectedresources
EnclosingProjects
WorkingSet
PressChoosetoselectorcreateaworkingset.
Searchresultview,filters
ThesearchresultsarepresentedintheSearchview.
TheViewMenucontainstheseoptions:
ShowAsList
Presentsresultsinaflatlist.Inthismode,thecontextmenucontainsaSortBymenuwithoptionsName,Path,ParentName.
ShowasTree
Presentsresultsinahierarchy.Inthismode,4buttonsappearintheviewtoolbar,whereyoucanGroupbyProject,Package,File,orType.
Filters
Variousfiltersallowtoexcludecertainsearchresults,forexamplepotentialmatches,matchesinimports,Javadocs,deprecated,nonpublic,staticornonstaticelements.
Fortypes,therearefiltersforinexactornonmatchingtypearguments.
Formethods,there'safilterforreferencestooverridingmethods.
Forfields,therearefiltersforreadorwriteaccesses.
Javasearch
Search
5.8.JavaViewsandEditors
Javaeditor
Javaviews
Javadevelopmenttools(JDT)
Changingtheappearanceoftheconsoleview
Openinganeditorforaselectedelement
Openinganeditoronatype
Javaeditoractions
Breakpointsview
Consoleview
Debugview
Displayview
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 197/322
12/10/2015 Javadevelopmentuserguide
Expressionsview
Javaeditor
PackageExplorerview
Variablesview
Javaoutline
JavascrapbookPage
TypeHierarchyview
CallHierarchyview
5.8.1.BreakpointsView
TheBreakpointsViewlistsallthebreakpointsyoucurrentlyhavesetinyourworkspace.
Youcandoubleclickabreakpointtodisplayitslocationintheeditor(ifapplicable).Youcanalsoenableordisablebreakpoints,deletethem,addnewones,groupthembyworking
set,orsethitcounts.
IntheexampleshownbelowtheGroupby>BreakpointTypesoptionisturnedon.
ThebreakpointsviewdisplaysdetailsoftheselectedbreakpointandcanbeusedtoconfigureattributesoftheselectedbreakpointsimilartotheBreakpointProperties...action.The
orientationofthedetailpanecanbeconfiguredfromtheviewdropdownmenu.
ThecommandsavailableintheBreakpointsViewarelistedbelow.
BreakpointsViewCommands
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 198/322
12/10/2015 Javadevelopmentuserguide
Paste Pastescopiedbreakpointsintotheview. Contextmenu
Breakpoints
Javaviews
Javaperspectives
Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints
Viewsandeditors
5.8.1.1.WatchpointAccess
SelecttheAccesscommandtochangeifthecurrentlyselectedwatchpointwillsuspendwhenitsassociatedfieldisaccessedorread.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
WatchpointAccessOption
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 199/322
12/10/2015 Javadevelopmentuserguide
5.8.1.2.AddJavaExceptionBreakpoint
SelecttheAddExceptionBreakpointcommand[ ]toaddaJavaexceptionbreakpoint.
Intheresultingdialog:
IntheChooseanExceptionfield,typeastringthatiscontainedinthenameoftheexceptionyouwanttoadd.Youcanusewildcardsasneeded("*"foranystringand"?"for
anycharacter).
IntheMatchingtypeslist,selecttheexceptionyouwanttoadd.
SelectCaughtandUncaughtasneededtoindicateonwhichexceptiontypeyouwanttosuspendtheprogram.
TheAddJavaExceptionBreakpointDialog.
Breakpoints
CatchingJavaexceptions
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
RunMenu
CaughtExceptionOption
UncaughtExceptionOption
5.8.1.3.BreakpointProperties...
SelecttheBreakpointProperties...commandtoopenthebreakpointpropertiesdialogforthecurrentlyselectedbreakpoint.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 200/322
12/10/2015 Javadevelopmentuserguide
Thereareseparatepropertiesforeachtypeofbreakpoint,thusresultinginvaryingpropertiesdialogs.Theexamplegivenbelowisforalinebreakpoint.
Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints
BreakpointsView
Conditionoption
Enabledoption
Hitcountoption
Exceptionbreakpointcaughtoption
Exceptionbreakpointsuspendonsubclassoption
Exceptionbreakpointuncaughtoption
Methodbreakpointentryoption
Methodbreakpointexitoption
SuspendPolicy
Watchpointaccessoption
Watchpointmodificationoption
5.8.1.4.ExceptionBreakpointCaught
SelecttheCaughtcommandtochangeifthecurrentlyselectedJavaexceptionbreakpointwillsuspendoncaughtexceptionsofthesametype.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 201/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
CatchingJavaexceptions
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
CaughtExceptionOption
5.8.1.5.CollapseAll
SelecttheCollapseAllcommand[ ]tocollapseallofthecurrentlyelementsintheview.
Thiscommandappliesto:
BreakpointsView
ExpressionsView
RegistersView
VariablesView
5.8.1.6.Copy
SelecttheCopycommand[ ]tocopytheselectedcontentsfromtheviewontothesystemclipboard.YoucanalsousethestandardkeyboardshortcutCtrl+C.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DebugView
DisplayView
ExpressionsView
RegistersView
VariablesView
DetailPane(intheExpressionsViewandVariablesView)
5.8.1.7.DisableBreakpoints
SelecttheDisablecommand[ ]todisablethecurrentlyselectedbreakpoint(s).
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 202/322
12/10/2015 Javadevelopmentuserguide
BreakpointsView
BreakpointEnabledOption
5.8.1.8.EnableBreakpoints
SelecttheEnablecommand[ ]toenablethecurrentlyselectedbreakpoint(s).
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
BreakpointEnabledOption
5.8.1.9.MethodBreakpointEntry
SelecttheEntrycommandtochangeiftheselectedmethodbreakpointwillsuspendonentrytotheassociatedmethod.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
MethodBreakpointEntryOption
5.8.1.10.MethodBreakpointExit
SelecttheExitcommandtochangeiftheselectedmethodbreakpointwillsuspendonexitfromtheassociatedmethod.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 203/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
MethodBreakpointExitOption
5.8.1.11.ExpandAll
SelecttheExpandAllcommand[ ]toexpandalloftheitemsintheBreakpointsView.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.12.ExportBreakpoints
SelecttheExportBreakpoints...command[ ]tostartthe ExportBreakpointswizardwhichwillhelpyouexportbreakpointstoafile.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
ExportBreakpointswizard
ImportBreakpointswizard
ImportBreakpointscommand
5.8.1.13.GotoFileforBreakpoint
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 204/322
12/10/2015 Javadevelopmentuserguide
SelecttheGotoFilecommand[ ]toopentheassociatedresourceforthebreakpoint,makeitactiveandhighlightthelocationofthebreakpoint.Iftheresourceisalreadyopenit
ismadeactiveandthebreakpointlocationishighlighted.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.14.GroupBreakpointsBy
SelecttheGroupByviewmenuitemtogroupthebreakpointsintheBreakpointsViewinoneofachoiceofpredefinedorderings.
Theorderingsareasfollows:
Breakpointsastandardlistofallbreakpoints
BreakpointTypesallbreakpointsorganizedintotheirrespectivetypes
BreakpointWorkingSetsallbreakpointsareorganizedintotheworkingsetstheybelongto
Filesallbreakpointsareorganizedbythefilesthattheybelongto
Projectsallbreakpointsareorganizedbytheprojectthattheybelongto
ResourceWorkingSetsallbreakpointsareorganizedbytheresourceworkingsetsthattheybelongto
Advanced...Seebelow.
TheAdvanced...commandopensadialogthatallowsyoutospecifymultiplelevelsofgroupingsforyourbreakpoints.Forexampleyoucouldhavebreakpointgroupedbytype,
whicharethenfurthergroupedbyresourceworkingset,whicharethenfurthergroupedbyprojects.
BelowistheGroupBreakpointsdialog.
Breakpoints
Addingbreakpoints
Createabreakpointworkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 205/322
12/10/2015 Javadevelopmentuserguide
BreakpointsView
5.8.1.15.BreakpointHitCount
SelecttheHitCountcommand[ ]toeditthehitcountforthecurrentlyselectedbreakpoint.
ThecommandopenstheSetBreakpointHitCountdialogwhichallowsyoutoenteranintegervaluehitcounttoapplytotheselectedbreakpoint.
TheSetBreakpointHitCountDialog.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
BreakpointHitCountOption
5.8.1.16.ImportBreakpoints
SelecttheImportBreakpoints...command[ ]tostartthe ImportBreakpointswizardwhichwillhelpyouimportbreakpointsintoyourworkspace.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
ExportBreakpointswizard
ImportBreakpointswizard
ExportBreakpointscommand
5.8.1.17.LinkBreakpointsViewwithDebugView
SelecttheLinkwithDebugViewcommand[ ]tohavetheBreakpointsViewbeupdatedwithinformationfromtheDebugView.Whenanapplicationsuspendsonabreakpoint
intheDebugView,theassociatedbreakpointwillbehighlightedintheBreakpointsView.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.18.WatchpointModification
SelecttheModificationcommandtochangeifthecurrentlyselectedwatchpointwillsuspendwhenitsassociatedfieldismodifiedorwrittento.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 206/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
WatchpointModificationOption
5.8.1.19.Paste
SelectthePastecommand[ ]tocopymaterialfromthesystemclipboardintothecurrentview.YoucanalsousethestandardkeyboardshortcutCtrl+V.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
5.8.1.20.RemoveSelectedBreakpoint
SelecttheRemovecommand[ ]toremovetheselectedbreakpoint(s)fromtheBreakpointsView.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.21.RemoveAllBreakpoints
SelecttheRemoveAllcommand[ ]toremoveallbreakpointsfromtheBreakpointsView.
Breakpoints
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 207/322
12/10/2015 Javadevelopmentuserguide
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.22.SelectAll
Choosethiscommandtoselectallofthecontentintheview.YoucanalsousethestandardkeyboardshortcutCtrl+A.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DisplayView
ExpressionsView
RegistersView
VariablesView
DetailPane(intheExpressionsViewandVariablesView)
5.8.1.23.SelectDefaultBreakpointWorkingSet
ChoosetheSelectDefaultWorkingSet...command[ ]toselectadefaultworkingset.
ThecommandopenstheSelectDefaultWorkingSetdialog,whichisthenusedtoselectaworkingsettobethedefault.
Breakpoints
Addingbreakpoints
CreateWorkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.24.ShowQualifiedNames
SelecttheShowQualifiedNamescommand[ ]thechangewhetherqualifiednamesshouldbeshownintheviewornot.
Thiscommandappliesto:
BreakpointsView
ExpressionsView
VariablesView
ViewDisplayCommands
5.8.1.25.ShowSupportedBreakpoints
SelecttheShowSupportedBreakpointscommand[ ]toindicateifonlybreakpointsapplicabletothecurrentdebugtargetshouldbevisibleintheBreakpointsView.
Example:IfyouhaveC/C++andJavabreakpoints,withthisoptionturnedonyouwillonlyseethosebreakpointsapplicabletowhatyouarecurrentlydebugging.Meaningthatwhen
youaredebuggingaJavaprogramtheBreakpointsViewwillonlydisplayJavabreakpoints.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 208/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.26.SkipAllBreakpoints
SelecttheSkipAllBreakpointscommand[ ]tomarkallbreakpointsinthecurrentviewasskipped.Breakpointsmarkedasskippedwillnotsuspendexecution.
TheBreakpointsViewshowingallbreakpointsmarkedasskipped.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.27.BreakpointSuspend
SelecttheSuspendcommand[ ]tochangethesuspendpolicyofabreakpointbetweensuspendingtheentireVMandthethreadinwhichthebreakpointsuspended.
Thereisonlyonemenuitemvisibleatanyonegiventime,showingyouwhichsuspendpolicyyouwillbechangingtoshouldyouselectit.
Youcanchangethedefaultsuspendpolicyforallnewlycreatedbreakpointsonthe Java>Debugpreferencepage.
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
BreakpointSuspendPolicyOption
5.8.1.28.BreakpointViewWorkingSets
SelecttheWorkingSets...commandtoopentheworkingsetsdialog,whichallowsyoutoadd/remove/editworkingsets.
TheWorkingSet...command.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 209/322
12/10/2015 Javadevelopmentuserguide
TheSelectWorkingSetdialog.
Breakpoints
Addingbreakpoints
CreateWorkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
5.8.1.29.ExceptionBreakpointUncaught
SelecttheUncaughtcommandtochangeiftheselectedJavaexceptionbreakpointwillsuspendforuncaughtexceptionsofthesametype.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 210/322
12/10/2015 Javadevelopmentuserguide
Breakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging
BreakpointsView
ExceptionBreakpointUncaughtOption
5.8.2.ConsoleView
TheConsoleViewdisplaysavarietyofconsoletypesdependingonthetypeofdevelopmentandthecurrentsetofusersettings.
ThethreeconsolesthatareprovidedbydefaultwiththeEclipsePlatformare:
TheProcessConsole
TheStacktraceConsole
TheCVSConsole
Youcanchangesettingsforconsolesonthe Run/Debug>Consolepreferencepage.
ThecommandsavailableintheConsoleViewarelistedbelow.
ConsoleViewCommands
Contextmenuandviewaction
ClearConsole Clearsthecurrentlyactiveconsole,andisavailableasbothaviewcommandanda
contextualmenuitem.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsolePreferences
CVSConsole
ProcessConsole
StacktraceConsole
Viewsandeditors
5.8.2.1.CVSConsole
TheCVSConsoledisplaystheoutputfromcurrentandrecentCVSoperations.
TheextracommandsavailableintheCVSConsolearelistedbelow.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 211/322
12/10/2015 Javadevelopmentuserguide
CVSConsoleCommands
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
ProcessConsole
StacktraceConsole
5.8.2.1.2.Cut
SelecttheCutcommand[ ]tocopytheselectedcontentsfromtheviewtothesystemclipboardandremovetheselectionfromtheview.Youcanalsousethestandardkeyboard
shortcutCtrl+X.
Thiscommandappliesto:
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
5.8.2.1.3.Find/Replace
SelecttheFind/Replacecommandtosearchforandreplacespecificstatementsorportionsofstatements.YoucanalsousethekeyboardshortcutCtrl+F.
Theresultingfind/replacedialog.
Thiscommandappliesto:
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
5.8.2.1.4.OpenLink
SelecttheOpenLinkcommandtofollowadetectedhyperlinkintheStacktraceConsoleortheCVSConsole.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 212/322
12/10/2015 Javadevelopmentuserguide
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.ProcessConsole
TheProcessConsoleshowstheoutputofaprocessandallowsyoutoprovidekeyboardinputtoaprocess.
TheProcessConsoleshowsthreedifferentkindsoftext:
Standardoutput
Standarderror
Standardinput
Youcanchoosethedifferentcolorsforthesekindsoftextonthe Run/Debug>Consolepreferencepage.
TheextracommandsavailableintheProcessConsolearelistedbelow.
ProcessConsoleCommands
Javaviews
Javaperspectives
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 213/322
12/10/2015 Javadevelopmentuserguide
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
StacktraceConsole
CVSConsole
5.8.2.2.3.ConsolePreferences
SelectthePreferences...commandtoopenthe Run/Debug>Consolepreferencepage.
ThiscommandonlyappliestotheProcessConsole.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.6.RemoveAllTerminatedLaunches
SelecttheRemoveAllTerminatedcommand[ ]toremovealloftheterminatedlaunchesfromtheProcessConsole.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.7.RemoveLaunch
SelecttheRemoveLaunchcommand[ ]toremovethecurrentlaunchfromtheProcessConsole.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 214/322
12/10/2015 Javadevelopmentuserguide
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.9.ShowConsoleWhenStandardOutChanges
SelecttheShowConsoleWhenStandardOutChangescommand[ ]tohaveaconsoleopened(ifnotopenalready)andbroughttothefrontiftheassociatedprocessofthe
currentProcessConsolewritestoStandard.out.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.10.ShowConsoleWhenStandardErrorChanges
SelecttheShowConsoleWhenStandardErrorChangescommand[ ]tohaveaconsoleopened(ifnotopenalready)andbroughttothefrontiftheassociatedprocessofthe
currentProcessConsolewritestoStandard.err.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.2.11.Terminate
SelecttheTerminatecommand[ ]toterminatetheprocessthatisassociatedwiththecurrentProcessConsole.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.3.StacktraceConsole
TheStacktraceConsoledisplaysaJavastacktraceinanicelyformattedmanner,providinghyperlinksupporttoquicklyjumptosourcecodelocations.
TheextracommandsavailableintheStacktraceConsolearelistedbelow.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 215/322
12/10/2015 Javadevelopmentuserguide
StacktraceConsoleCommands
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
5.8.2.3.1.ConsoleAutoformat
SelecttheAutoformatcommand[ ]toautomaticallyreformatanystacktracepastedintotheStacktraceConsole.
Thiscommandisonlyavailabletostacktraceconsoles.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
5.8.2.3.5.ConsoleFormat
SelecttheFormatcommandtoreformatthecurrentstacktraceintheStacktraceConsole.YoucanalsousethekeyboardshortcutCtrl+Shift+F.
Thiscommandisonlyavailabletostacktraceconsoles.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 216/322
12/10/2015 Javadevelopmentuserguide
ConsoleView
CVSConsole
ProcessConsole
5.8.2.4.ClearConsole
SelecttheClearConsolecommand[ ]toclearallofthecontentsintheConsoleView.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.5.DisplaySelectedConsole
SelecttheDisplaySelectedConsolecommand[ ]tobringtheconsoleselectedfromtheresultinglistintofocus.
Note:thiscommandisonlyenabledifyouhavemorethanoneconsoleopen.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.6.OpenConsole
SelecttheOpenConsolecommand[ ]toopenanewspecifictypeofconsoleintheConsoleView.
Theresultingmenufromselectingthedropdownarrowonthecommand.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.7.PinConsole
SelectthePinConsolecommand[ ]toensurethatthecurrentconsoleremainsontopofallotherconsoles.
Forexampleifyouhadtwoconsoles,sayaProcessConsoleandaStacktraceConsole,andyouhadthestacktraceconsolepinned,evenifoutputiswrittentotheprocess
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 217/322
12/10/2015 Javadevelopmentuserguide
consoleitwillnotcometofocusinfrontofthestacktraceconsole.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.2.8.ScrollLock
SelecttheScrollLockcommand[ ]tochangewhetherscrolllockshouldbeenabledordisabledforallopenconsoles.
Javaviews
Javaperspectives
Changingtheappearanceoftheconsoleview
Viewsandeditors
ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole
5.8.3.DebugView
TheDebugViewallowsyoutomanagethedebuggingorrunningofaprogramintheworkbench.Itdisplaysthestackframeforthesuspendedthreadsforeachtargetyouare
debugging.Eachthreadinyourprogramappearsasanodeinthetree.Itdisplaystheprocessforeachtargetyouarerunning.
Ifthethreadissuspended,itsstackframesareshownaschildelements.
TheExecutionControlCommandsallowyoutodebugyourprogram,starting,stoppingandsteppingthroughthecode.
DebugViewCommands
Automatic Configuresthedebugviewtoswitchlayoutbetweenatreeandabreadcrumbviewerautomaticallywhentheviewis
Viewaction
resized.
AutoExpand ConfigurestheDebugBreadcrumbDropdowntoautomaticallyexpandelementswhenopened.
Viewaction
Breadcrumb
Breadcrumb Configuresthedebugviewlayouttouseabreadcrumbviewer. Viewaction
Contextmenuand
Disconnect Disconnectsthedebuggerfromtheselecteddebugtargetwhendebuggingremotely.
viewaction
DroptoFrame Thiscommandletsyoudropbackandreenteraspecifiedstackframe.Thisfeatureissimilarto"runningbackwards"
andrestartingyourprogrampartwaythrough.
Todropbackandreenteraspecifiedstackframe,selectthestackframethatyouwantto"drop"to,andselectDrop
toFrame.
Contextmenuand
Somecaveatsapplytothisfeature: viewaction
Youcannotdroppastanativemethodonthestack.
Globaldataareunaffectedandwillretaintheircurrentvalues.Forexample,astaticvectorcontainingelements
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 218/322
12/10/2015 Javadevelopmentuserguide
willnotbecleared.
Note:ThiscommandisonlyenablediftheunderlyingVMsupportsthisfeature.
Edit[configuration Opensthelaunchconfigurationdialogontheassociatedlaunchconfiguration,allowingyoutomakechanges.
Contextmenu
name]...
EditStepFilters OpenstheStepFilteringpreferencepagetoallowingeditingofstepfilters Contextmenu
EditSourceLookup Opensthesourcelookupdialog,allowingyoutomakechanges. Contextmenu
Contextmenu,Run
Resume Resumesasuspendedthread.
menuandviewaction
ShowMonitors
Thisoptioncanbetoggledtodisplayorhidemonitors.
Viewaction
Note:thiscommandwillonlydisplaymonitorinformationiftheunderlyingVMsupportsit.
ShowQualified Thisoptioncanbetoggledtodisplayorhidequalifiednames.
Viewaction
Names
ShowSystem Thisoptioncanbetoggledtodisplayorhidesystemthreads
Viewaction
Threads
ShowThreadGroups Thisoptioncanbetoggledtodisplayorhidethreadgroups Viewaction
Contextmenu,Run
StepInto Stepsintothehighlightedstatement.
menuandviewaction
StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyouare
attheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. Contextmenu,Run
menuandviewaction
Thecursorjumpstothedeclarationofthemethodandselectsthisline.
Contextmenu,Run
StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod.
menuandviewaction
Contextmenu,Run
Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.
menuandviewaction
Contextmenu,Run
Terminate Terminatestheselecteddebugtarget.
menuandviewaction
Terminate/Disconnect Terminatesallactivelaunchesintheview.
Contextmenu
All
Terminateand Terminatestheselecteddebugtargetandrelaunchesit.
Contextmenu
Relaunch
Terminateand Terminatestheselecteddebugtargetandremovesitfromtheview.
Contextmenu
Remove
Tree Configuresthedebugviewlayouttouseatreeviewer. Viewaction
Debugger
Javaviews
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 219/322
12/10/2015 Javadevelopmentuserguide
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugPreferences
Viewsandeditors
RunMenu
5.8.3.1.ExecutionControlCommands
Executioncontrolcommandsallowyoutochangetheexecutionstateofcodebeingexecuted.
JavaExecutionControlCommands
Contextmenu,Run
Resume Resumesasuspendedthread.
menuandviewaction
Contextmenu,Run
StepInto Stepsintothehighlightedstatement.
menuandviewaction
StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyouare
attheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. Contextmenu,Run
menuandviewaction
Thecursorjumpstothedeclarationofthemethodandselectsthisline.
Contextmenu,Run
StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod.
menuandviewaction
Contextmenu,Run
Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.
menuandviewaction
Contextmenu,Run
Terminate Terminatestheselecteddebugtarget.
menuandviewaction
Terminate& Terminatestheselecteddebugtargetandrelaunchesit.
Contextmenu
Relaunch
Terminate/Disconnect Terminatesallactivelaunchesintheview.
Contextmenu
All
SeetheDebugViewformoreinformation.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
RunMenu
5.8.3.1.1.Resume
SelecttheResumecommand[ ]toresumetheexecutionofthecurrentlysuspendeddebugtarget.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 220/322
12/10/2015 Javadevelopmentuserguide
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
5.8.3.1.2.StepInto
SelecttheStepIntocommand[ ]tostepintothenextmethodcallatthecurrentlyexecutinglineofcode.
Tostepintoamethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepReturn
StepOver
5.8.3.1.3.StepOver
SelecttheStepOvercommand[ ]tostepoverthenextmethodcall(withoutenteringit)atthecurrentlyexecutinglineofcode.Eventhoughthemethodisneversteppedinto,the
methodwillbeexecutednormally.
Tostepoveramethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepReturn
StepInto
5.8.3.1.4.StepReturn
SelecttheStepReturncommand[ ]toreturnfromamethodwhichhasbeensteppedinto.Eventhoughwereturnfromthemethod,theremainderofthecodeinsidethemethod
willbeexecutednormally.
Tostepreturnfromamethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 221/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepInto
StepOver
5.8.3.1.5.Suspend
SelecttheSuspendcommand[ ]tohalttheexecutionofthecurrentlyselectedthreadinadebugtarget.Oncetheselectedthreadissuspendedyoucanthenexamineitsstack
frames.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
Resume
RunMenu
5.8.3.1.6.Terminate
SelecttheTerminatecommand[ ]toterminatethelaunchassociatedwiththeselecteddebugtarget.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
RunMenu
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 222/322
12/10/2015 Javadevelopmentuserguide
5.8.3.1.7.Terminate/DisconnectAll
SelecttheTerminate/DisconnectAllcommand[ ]toterminatealltherunningdebugtargetsintheDebugandConsoleView.Ifthetargetcannotbeterminated,itwillbe
disconnected.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugandConsoleView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
ConsoleView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
Terminate
TerminateandRelaunch
TerminateandRemove
5.8.3.1.8.TerminateandRelaunch
SelecttheTerminateandRelaunchcommand[ ]tofirstterminatetheselecteddebugtargetandsecondly,relaunchit.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RemoveAllTerminatedLaunches
Terminate
Terminate/DisconnectAll
TerminateandRemove
5.8.3.1.9.TerminateandRemove
SelecttheTerminateandRemovecommand[ ]toterminatethelaunchassociatedwiththeselecteddebugtargetandremoveitfromtheDebugView.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 223/322
12/10/2015 Javadevelopmentuserguide
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
Terminate
Terminate/DisconnectAll
TerminateandRelaunch
5.8.3.3.Disconnect
SelecttheDisconnectcommand[ ]toterminatetheconnectionbetweenthedebuggerandtheremotedebugtarget.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.4.DroptoFrame
SelecttheDroptoFramecommand[ ]toreentertheselectedstackframeintheDebugView.
NotethiscommandisonlyavailableifthecurrentVMsupportsdroptoframeandtheselectedstackframeisnotthetopframeoraframeinanativemethod.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.5.Edit...
SelecttheEdit...commandtoopentheLaunchConfigurationDialog,andallowyoutoeditthelaunchconfigurationfortheselectedtarget.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 224/322
12/10/2015 Javadevelopmentuserguide
Theresultinglaunchconfigurationdialog,inthisexampleaJavaApplicationtype.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.6.EditSourceLookup
SelecttheEditSourceLookup...command[ ]toopentheSourcePathDialog,whichallowsyoutomakechangestothesourcelookuppathoftheselecteddebugtarget.
TheSourcePathDialog:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 225/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.7.EditStepFilters
SelecttheEditStepFilterscommandtoopenthe Java>Debug>StepFilteringpreferencepage,whichallowsyoutoaddandconfigurestepfilters.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 226/322
12/10/2015 Javadevelopmentuserguide
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
FilterPackageCommand
FilterTypeCommand
UseStepFiltersCommand
5.8.3.8.FilterPackage
SelecttheFilterPackagecommandtoaddthepackageoftheselectedstackframetothelistofitemstobefilteredviastepfiltering.
Forexample,ifthecurrentlyselectedstackframeisoftypejava.lang.Object,andyouselecttheFilterPackagecommandthenjava.lang.*willbeaddedtothelistoftypestobe
filteredviastepfiltering.
Warning:Youcaninadvertentlyfilteroutmorethanyouexpectwhenusingthiscommand,takecareinitsuse.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
EditStepFiltersCommand
FilterTypeCommand
UseStepFiltersCommand
5.8.3.9.FilterType
SelecttheFilterTypecommandtoaddthetypeassociatedwiththeselectedstackframetothelistoftypestobefilteredviastepfiltering.
Forexample,ifthecurrentlyselectedstackframeisassociatedwiththetypejava.lang.Object,andyouselecttheFilterTypecommandthenjava.lang.Objectwillbeaddedtothe
listoftypestobefilteredviastepfiltering.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 227/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
StepCommands
EditStepFiltersCommand
UseStepFiltersCommand
FilterPackageCommand
5.8.3.10.Find...
SelecttheFind...commandtoopentheFindDialogwhichallowsyoutosearchforspecificelementswithintheview.YoucanalsousethekeyboardshortcutCtrl+F.
TheFindDialog:
Thiscommandappliesto:
DebugView
ExpressionsView
RegistersView
VariablesView
5.8.3.11.LookupSource
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 228/322
12/10/2015 Javadevelopmentuserguide
SelecttheLookupSourcecommandtoforceasourcelookuptotakeplace.Iftherequestedsourcefileisnotopen,itwillbeopenedandthecorrespondinglineofexecutionwillbe
highlighted.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
EditSourceLookup
5.8.3.12.OpenDeclaredType
SelecttheOpenDeclaredTypecommandtoopenaneditoronthedeclaredtypeofthecurrentlyselectedstackframeintheDebugView.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 229/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.13.OpenDeclaredTypeHierarchy
SelecttheOpenDeclaredTypeHierarchycommandtoopenthedeclaredtypeofthecurrentlyselectedstackframeintheTypeHierarchyView.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 230/322
12/10/2015 Javadevelopmentuserguide
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.14.Properties
SelectthePropertiescommandtoopenthepropertiesdialogfortheselecteddebugtarget,thread,threadgroup,processorstackframe.
Fromtheresultingdialogyoucancopyinformationabouttheselecteddebugtargetandviewtheactualcommandlineusedtorunthetarget.
YoucanalsoviewthecapabilitiesoftheVMusedtolaunchtheassociatedtarget
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 231/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
5.8.3.15.Relaunch
SelecttheRelaunchcommand[ ]torelaunchtheselecteddebugtargetintheDebugView.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
RemoveAllTerminatedLaunches
RunMenu
Terminate
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove
5.8.3.16.RemoveAllTerminated
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 232/322
12/10/2015 Javadevelopmentuserguide
SelecttheRemoveAllTerminatedcommand[ ]tocleartheDebugViewofallterminatedlaunches.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
Relaunch
Terminate
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove
5.8.3.17.ShowMonitors
SelecttheShowMonitorscommand[ ]tochangeifmonitorinformationwillbeshownforsuspendedthreads.
Note:ThedisplayofmonitorinformationmustbesupportedbytheunderlyingVM.IfusinganIBMorSUNVM,anyversiongreaterthan1.4willsupportmonitorinformation.
Considerthefollowingcodeexample:
/**
*HelloWorld
*/
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
Objectmutex=newObject()
synchronized(mutex){
System.out.println("HelloWorld!")
}
}
}
IftheabovecodesnippetisrunonasupportingVMwithShowMonitorsselected,themonitorinformationisrepresentedasa'key'andappearingbeforeanystackframesasachild
ofasuspendedthread.
Ifhowever,werunthesamesnippetonanunsupportedVMwithShowMonitorsselected,wearealertedthatmonitorinformationisnotsupportedbytheVM.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 233/322
12/10/2015 Javadevelopmentuserguide
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ShowSystemThreads
ShowThreadGroups
5.8.3.19.ShowSystemThreads
SelecttheShowSystemThreadscommand[ ]tochangeifsystemthreadsshouldbeshownintheDebugView.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ShowMonitors
ShowSystemThreads
ShowThreadGroups
5.8.3.20.ShowThreadGroups
SelecttheShowThreadGroupscommand[ ]tochangeifthreadgroupsshouldbeusedtoorganizethreadsdisplayedintheDebugView.
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ShowMonitors
ShowSystemThreads
ShowThreadGroups
5.8.3.21.UseStepFilters
SelecttheUseStepFilterscommand[ ]tochangewhetherstepfiltersshouldbeusedintheDebugView.YoucanalsousethekeyboardshortcutShift+F5.
Stepfiltersarecommonlyusedtofilterouttypesthatyoudonotwishtoseeorstepthroughwhiledebugging.
Forexample,ifyoudidnotwanttotheseeorstepthroughanythingfromtheclassjava.lang.Object,youwouldaddthistothelistoffilteredtypes.Addingtypestothelistofthose
tobefilteredcanbedoneinoneoftwoways:
1. ViathecontextmenuRightclickonthestackframeforthetypeyouwishtofilterandusetheFilterTypeorFilterPackagecommand.
2. Viathe Java>Debug>StepFilteringpreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 234/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads
DebugView
Debugpreferences
ExecutionControlCommands
EditStepFilters
RunMenu
5.8.4.DisplayView
TheDisplayViewdisplaystheresultofevaluatinganexpressioninthecontextofthecurrentstackframe.Youcanevaluateanddisplayaselectioneitherfromtheeditorordirectly
fromtheDisplayView.
Thecommandsavailableinthedisplayviewarelistedbelow.
DisplayViewCommands
Javaviews
Javaperspectives
Evaluatingexpressions
Viewsandeditors
5.8.4.1.Clear
SelecttheClearcommand[ ]toremoveallofthecontentsfromtheview.
DisplayView
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 235/322
12/10/2015 Javadevelopmentuserguide
5.8.4.2.ContentAssist
SelecttheContentAssistcommand[ ]toopentheContentAssistpopupdialog.YoucanalsousethekeyboardshortcutCtrl+Spacebarwithintheview.
Theresultingdialogprovidesyouwithcontextsensitivecodinghelpbymakingavailablealistingofallapplicablejavacodeelementsforthelocationcontentassistwasactivated.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
EvaluatingExpressions
5.8.4.5.Display
SelecttheDisplaycommand[ ]tohavetheselectedstatementevaluatedandtheresultsdisplayedinlineintheDisplayVieworinapopupdialog(thatcanbemovedtothe
DisplayView).
Forexample,considerwehavethefollowingstatementselectedintheDisplayView:
AfterweselecttheDisplaycommandwenoticethattheresultisinsertedinlineintheview.Inthefollowingcasethough,aprintln()statementdoesnothaveanexplicitreturn
value,sothatiswhatiswrittenintheview.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu
EvaluatingExpressions
5.8.4.6.Execute
SelecttheExecutecommand[ ]tohavetheselectedstatementexecutedasthoughitwasruninnormalJavacode.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 236/322
12/10/2015 Javadevelopmentuserguide
EvaluatingExpressions
5.8.4.8.InspectSelectedStatement
SelecttheInspectcommand[ ]toevaluatetheselectedexpressionandhaveitsresultdisplayedinapopupbox.
YoucanalsomovetheinspectedstatementtotheExpressionsViewbypressingCtrl+Shift+Ioncethepopuphasbeenopened.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu
EvaluatingExpressions
5.8.5.ExpressionsView
DatacanbeinspectedintheExpressionsView.Youcaninspectdatafromascrapbookpage,astackframeofasuspendedthread,andotherplaces.TheExpressionsViewopens
automaticallywhenanitemisaddedtotheview.EntriesintheExpressionsViewcanbeselectedtohavemoredetailedinformationbedisplayedintheDetailPane.When
debuggingaJavaprogram,datathatcontainsvariablescanbeexpandedtoshowthevariablesandthefieldsthevariablescontain.
TheExpressionsView.TheDetailPaneistheareaatthebottomoftheviewdisplayingtext..
TherearemanycommandsavailableintheExpressionsView:
ViewDisplayCommandsaffectwhatdataandvariablesaredisplayedandhowtheyarepresented.
TheDetailPanehasmanycommandsavailablebyrightclickingonit.
ViewLayoutCommandsaffecthowthedetailpaneisoriented.
Othercommandsarelistedbelow.
VariablesViewCommands
AddWatch Allowsyoutoaddawatchexpression.
Contextmenu
Expression
AllInstances OpensapopupdialogdisplayingalistofallinstancesoftheselectedJavatype.YourJavavirtualmachinemustsupport
Contextmenu
instanceretrieval.
AllReferences OpensapopupdialogdisplayingalistofallJavaobjectsthathavereferencestotheselectedvariable.YourJavavirtual
Contextmenu
machinemustsupportreferenceretrieval.
ChangeValue... Allowsyoutochangethevaluefortheunderlyingselectedvariable. Contextmenu
ConverttoWatch Convertstheselectedinspectexpressiontoacorrespondingwatchexpression.
Contextmenu
Expression
Disable Disablesacurrentlyenabledexpression. Contextmenu
EditLogicalStructure Allowyoutoeditthelogicalstructureoftheselectedvariable Contextmenu
EditWatch Allowsyoutoeditthecurrentlyselectedexpression.
Contextmenu
Expression
Enable Enablesacurrentlydisabledexpression. Contextmenu
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 237/322
12/10/2015
Enable Enablesacurrentlydisabledexpression. Javadevelopmentuserguide Contextmenu
Find... Opensthesearchdialogtofindelementsinthevariablesview. Contextmenu
Inspect Createsanewinspectexpressionfortheselectedvariableandaddsittotheview. Contextmenu
Javaviews
Javaperspectives
Scrapbook
Evaluatingexpressions
Suspendingthreads
DetailPane
ViewDisplayCommands
ViewLayoutCommands
5.8.5.1.DetailPane
TheDetailPanedisplaysdetailedinformationaboutaselectioninthefollowingviews:
ExpressionsView
RegistersView
VariablesView
TheVariablesViewwiththedetailpanehighlighted.
Bydefault,theDetailPanedisplaysinformationasmarkeduptext(textishighlighted,bolded,underlined,etc.accordingtotoolspecificsettings).Forexample,whendebugginga
Javaprogram,theDetailPanedisplaystoString()valueofJavaobjects.
Ifothertypesofdetailpanesareavailable,theycanbeaccessedbyrightclickingonavariableandgoingtothe"ShowDetailsAs"menu.Thismenuwillnotbeavailableunless
thereismorethanonepossibletypeofdetailpaneforthecurrentselection.Themarkeduptextviewerdetailpanethatisavailablebydefaultistheonlydetailpaneprovidedbythe
Eclipseplatform.
AnumberofcommandsareavailableinthedefaultDetailPane.TheyareaccessedbyrightclickingtheDetailPanetoopenupacontextmenu.
DetailPaneCommands
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 238/322
12/10/2015 Javadevelopmentuserguide
ContentAssist OpenstheContentAssistpopupdialog,offeringcodecompletionhelp. Contextmenu
ExpressionsView
VariablesView
5.8.5.1.1.AssignValue
SelecttheAssignValuecommandtoassignanewvaluetothecurrentlyselectedvariablebyevaluatingthetextinthedetailpane.
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)
EvaluatingExpressions
5.8.5.1.8.ForceReturn
SelecttheForceReturncommandtoreturnfromthecurrentmethodwiththespecifiedvalue.
Youcanforceanearlyreturnfromamethod(onlyavailablewhendebuggingonaJavaSE6virtualmachine).Thisreturnsavaluefromthecurrentstackframewithoutexecutingany
moreinstructionsinthemethodandreleasesanylocksobtainedbysynchronizedblocks.AreturnvalueiscreatedbyselectinganexpressionandForceReturn(Alt+Shift+F).This
actionisavailablefromtheJavaeditor'scontextmenu,toplevelRunmenu,intheDisplayView,andinthedetailpaneoftheVariablesView.
Forcinganearlyreturnfromanonvoidmethodrequiresanexpressiontobeevaluated.Forexample,ifamethodwasgoingtoreturnfalseyoucouldreturnavalueoftrueby
selectinganexpressionintheDisplayViewandinvokingForceReturn.Inthefollowingexample,elementCountisnotequaltozero,andwouldreturnfalse(seedebughover
showingthevalueofelementCount).
FromtheDisplayView,wecouldenterthevaluewewantreturned,selectitandusetheForceReturncommandtoforcethemethodisEmpty()toreturnwiththatvalue(inthe
followingexamplewewillforceisEmpty()toreturnwiththevaluetrue).
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu
EvaluatingExpressions
5.8.5.1.10.MaxDetailPaneLength
TheMaxLength...commandtoopensadialogallowingyoutochangethemaximumnumberofcharactersdisplayedintheDetailPane
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 239/322
12/10/2015 Javadevelopmentuserguide
5.8.5.1.13.WrapText
SelecttheWrapTextcommandtochangeifthetextdisplayedintheDetailPaneshouldwrapatthepredefinedwidthornot.
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)
5.8.5.2.VariableDisplayCommands
Viewdisplaycommandsaffectwhatvariablesaredisplayedintheviewandhowtheyarepresented.
Thesecommandsapplyto(somecommandsapplytoadditionalviews):
ExpressionsView
VariablesView
TheShowTypeNamesandShowLogicalStructurescommandsareavailableontheviewtoolbar.Theotheractionscanbefoundinthedropdownmenuoftheviewasshown
below.
ViewDisplayCommands
ShowLogical Changeswhetherlogicalstructuresshouldbeshownintheview.
Viewaction
Structures
ShowNullArray Changewhethernullarrayentriesshouldbeshownintheview.
Viewaction
Entries
ShowReferences Changeswhetherreferencestovariablesshouldbedisplayedintheview.YourJavavirtualmachinemustsupportreference
Viewaction
retrieval.
ExpressionsView
VariablesView
DetailPane
5.8.5.2.1.ShowConstants
SelecttheShowConstantscommand[ ]tochangeifconstantsshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView
ViewDisplayCommands
5.8.5.2.2.ShowLogicalStructures
SelecttheShowLogicalStructurescommand[ ]tochangeiflogicalstructuresshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 240/322
12/10/2015 Javadevelopmentuserguide
RegistersView
VariablesView
ViewDisplayCommands
5.8.5.2.3.ShowNullArrayEntries
SelecttheShowNullArrayEntriescommandtochangeifnullarrayentriesshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView
ViewDisplayCommands
5.8.5.2.5.ShowReferences
SelecttheShowReferencescommand[ ]tochangeifreferencesshouldbedisplayedasvariablesintheview.Whenturnedon,eachJavavariablethatsupportsreferenceswill
haveanewchilditemwiththename"'<variablename>'referencedfrom:".ThisnewvariablecontainsalistofallJavaobjectsthatholdareferencetotheparentobject.Youcanget
atextlistinthedetailpanebyclickingonthereferencelistvariableorexplorethedetailsofeachreferencingobjectbyexpandingthevariables.
ReferenceswillonlyappearintheviewiftheJavaVirtualMachineyouareusingsupportsreferenceretrieval.
Thiscommandappliesto:
ExpressionsView
VariablesView
TheVariablesViewwithShowReferencesturnedon.Inthiscase,theMapisreferencesbyoneobject,aHashMap$EntrySet.
ViewDisplayCommands
5.8.5.2.6.ShowStaticFields
SelecttheShowStaticFieldscommand[ ]tochangeifstaticfieldsshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView
ViewDisplayCommands
5.8.5.2.7.ShowTypeNames
SelecttheShowTypeNamescommand[ ]tochangeiftypenamesshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView
ViewDisplayCommands
5.8.5.3.ViewLayoutCommands
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 241/322
12/10/2015 Javadevelopmentuserguide
ViewlayoutcommandsaffecttheorientationoftheDetailPaneintheview.Inaddition,theVariablesViewhascommandsthatallowyoutochangecolumnsettings.
Thesecommandsapplyto:
ExpressionsView
RegistersView
VariablesView
ThecommandsareavailableundertheLayoutmenu,whichisshownbelowintheVariablesView.
DetailPaneDisplayCommands
Displaysthedetailpaneatthebottomoftheview,aligningthepartsoftheviewvertically.
Vertical Viewaction
ExpressionsView
VariablesView
5.8.5.3.1.ShowColumns
SelecttheShowColumnscommand[ ]tochangeifcolumnsshouldbeusedtodisplayvariableinformationintheVariablesView.IfShowColumnsisturnedon,theSelect
Columnscommandwillbeavailable,allowingyoutochoosewhichcolumnsarevisible.
Thiscommandappliesto:
VariablesView
ViewLayoutCommands
5.8.5.3.2.SelectColumns
SelecttheSelectColumns...commandtoopenadialogthatwillallowyoutochoosewhichcolumnstodisplayintheVariablesView.
Intheresultingdialogyoucanselectwhichcolumnswillbedisplayed.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 242/322
12/10/2015 Javadevelopmentuserguide
Thiscommandappliesto:
VariablesView
ViewLayoutCommands
5.8.5.3.3.HorizontalLayout
SelecttheHorizontalcommand[ ]torevealtheDetailPaneandsetitinahorizontalalignmentwithintheview.
Thiscommandappliesto:
ExpressionsView
MemoryView
RegistersView
VariablesView
ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView
5.8.5.3.4.VerticalLayout
SelecttheVerticalcommand[ ]torevealtheDetailPaneandsetitinaverticalalignmentwithintheview.
Thiscommandappliesto:
ExpressionsView
MemoryView
RegistersView
VariablesView
ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView
5.8.5.3.5.ViewOnly
SelecttheViewOnlycommand[ ]tohidetheDetailPanewithintheview.Thenameofthecommandwillchangebasedonthecurrentview.Forexample,intheVariables
View,thecommandisnamed'VariablesViewOnly'.
Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 243/322
12/10/2015 Javadevelopmentuserguide
ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView
5.8.5.4.AddWatchExpression
SelecttheAddWatchExpressioncommand[ ]toopenthecreatenewexpressiondialog,whichallowsyoutocreateanewwatchexpressionandaddittotheExpressions
View.
Theaddwatchexpressiondialog.
Evaluatingexpressions
ExpressionsView
5.8.5.5.AllInstances
SelecttheAllInstancescommand[ ]toopenapopupcontainingalistofallJavaobjectinstancesoftheselectedtypethatexistinthecurrentdebugtarget.Thecommandhasa
keyboardshortcutofCtrl+Shift+N.ThiscommandisonlyavailableiftheJavavirtualmachineyouarecurrentlyusingsupportsinstanceretrieval.
Thetypetosearchforcanbeselectedinseveralways:
IntheJavaEditor,highlightorplacethecursorinthenameofatypeoraconstructorforatype.
IntheOutlineView,selectatypeorconstructor.
IntheExpressionsVieworVariablesView,selectaJavaobjectvariable.
Oncethepopuphasopened,youcanmovethelisttotheExpressionsViewbypressingCtrl+Shift+I.
Thereisamaximumnumberofinstancesthevirtualmachinewillreturn.Thismaximumcanbechangedonthe Java>Debug>HeapWalkingpreferencepage.
Thiscommandappliesto:
JavaEditor
OutlineView
ExpressionsView
VariablesView
EvaluatingExpressions
RunMenu
5.8.5.6.AllReferences
SelecttheAllReferences...command[ ]toopenapopupcontainingalistofallJavaobjectsinthecurrentdebugtargetthathavereferencestotheselectedvariable.The
selectedvariableintheviewmustbeaJavaobject.ThiscommandisonlyavailableiftheJavavirtualmachineyouarecurrentlyusingsupportsreferenceretrieval.
Oncethepopuphasopened,youcanmovethelisttotheExpressionsViewbypressingCtrl+Shift+I.
Thereisamaximumnumberofreferencesthevirtualmachinewillreturn.Thismaximumcanbechangedonthe Java>Debug>HeapWalkingpreferencepage.
Thiscommandappliesto:
ExpressionsView
VariablesView
EvaluatingExpressions
RunMenu
5.8.5.7.ChangeVariableValue
SelecttheChangeValue...command[ ]toopenadialoginwhichyoucanchangethevalueoftheselectedvariableorregister.
IntheVariablesView,ifvariablesaredisplayedinthecolumnform,variablevaluescanalsocanbechangedbydirectlyeditingthevalueinthecolumn.
WhendebuggingaJavaprogram,therearethreedifferenttypesofdialogsthatthiscommandcanopen.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 244/322
12/10/2015 Javadevelopmentuserguide
TheChangePrimitiveValueDialogisusedtochangethevalueofaprimitivesuchasanint,long,orchar.
TheChangeObjectValueDialogisusedtochangethevalueofanObject.Therearetwoformsofthisdialog.
Formostobjectsyoumustenteranexpressionthatwillbeevaluatedtogeneratetheresultingvalue.
However,wheneditingJavaStrings,youmayalsoenterliteraltext.
Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView
EvaluatingExpressions
5.8.5.10.ConverttoWatchExpression
SelecttheConverttoWatchExpressioncommandtoconvertthecurrentlyselectedinspectexpressiontoawatchexpression.
Note:theinspectexpressionisremovedfromtheviewoncethewatchexpressioniscreated.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 245/322
12/10/2015 Javadevelopmentuserguide
ExpressionsView
5.8.5.11.DisableWatchExpression
SelecttheDisablecommandtodisabletheselectedwatchexpression.
ExpressionsView
EnableWatchExpression
5.8.5.12.EditWatchExpression...
SelecttheEditWatchExpression...commandtoopentheeditingdialogfortheselectedwatchexpression.
Theeditwatchexpressioncommand.
Theresultingeditdialog.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 246/322
12/10/2015 Javadevelopmentuserguide
ExpressionsView
5.8.5.13.EnableWatchExpression
SelecttheEnablecommandtoenabletheselectedwatchexpression.Theexpressionmustbedisabledforthiscommandtobeavailable.
ExpressionsView
DisableWatchExpression
5.8.5.15.InspectSelectedVariable
SelecttheInspectcommand[ ]tocreateaninspectexpressionassociatedwiththeselectedvariableandaddittotheExpressionsView.
Thiscommandappliesto:
ExpressionsView
VariablesView
EvaluatingExpressions
5.8.5.16.ViewJavaPreferences
SelecttheJavaPreferences...commandtoopenthepreferencepagescontainingoptionsrelatingtotheVariablesViewandtheExpressionsView.
Therearefourpagesintotalthatareshown,allasentriesinthetreeonthelefthandsideofthePreferencesDialog.
Thesepagesare:
The Java>Debug>DetailFormatterspreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 247/322
12/10/2015 Javadevelopmentuserguide
The Java>Debug>HeapWalkingpreferencepage.
The Java>Debug>LogicalStructurespreferencepage.
The Java>Debug>PrimitiveDisplayOptionspreferencepage.
Thiscommandappliesto:
ExpressionsView
VariablesView
5.8.5.17.ReevaluateWatchExpression
SelecttheReevaluateWatchExpressioncommandtoforcetheselectedwatchexpressiontobeevaluated.
ExpressionsView
5.8.5.18.RemoveSelectedExpressions
SelecttheRemovecommand[ ]toremovetheselectedwatchexpression(s)fromtheExpressionsView.
Youcanalsoperformthissameactionbyselectingtheexpression(s)thatyouwishtoremoveandpressingtheDeletekey.
ExpressionsView
5.8.5.19.RemoveAllExpressions
SelecttheRemoveAllExpressionscommand[ ]theremovealloftheexpressionsfromtheExpressionsView.
ExpressionsView
5.8.5.21.ToggleFieldWatchpoint
SelecttheToggleWatchpointcommand[ ]tocreateanewwatchpointonthecurrentlyselectedfield.Wheneverthatfieldisaccessedormodified,executionwillbesuspended.
Iftheselectedfieldalreadyhasawatchpoint,selectingthiscommandwillremoveit.YoumustselectaJavafieldobjecttousethiscommand.
Thiscommandappliesto:
ExpressionsView
VariablesView
Breakpoints
Addingbreakpoints
5.8.6.PackageExplorerView
ThePackageExplorerview,shownbydefaultintheJavaperspective,showstheJavaelementhierarchyoftheJavaprojectsinyourworkbench.ItprovidesyouwithaJavaspecific
viewoftheresourcesshownintheNavigator.Theelementhierarchyisderivedfromtheproject'sbuildpaths.
Foreachproject,itssourcefoldersandreferencedlibrariesareshowninthetree.YoucanopenandbrowsethecontentsofbothinternalandexternalJARfiles.OpeningaJava
elementinsideaJARopenstheCLASSfileeditor,andifthereisasourceattachmentfortheJARfile,itscorrespondingsourceisshown.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 248/322
12/10/2015 Javadevelopmentuserguide
Toolbarbuttons
Command Name Description
Back Navigatestothemostrecentlydisplayedstateoftheviewwithadifferentelementatthetoplevel.
Forward Navigatestothestateoftheviewwithadifferentelementatthetoplevelthatwasdisplayedimmediatelyafterthecurrentstate.
Up Navigatestotheparentcontainerofthepackagethatiscurrentlydisplayedatthetoplevelintheview.
CollapseAll Collapsesalltreenodes.
LinkwithEditor Linksthepackageexplorer'sselectiontotheactiveeditor.
TopLevelElements> ShowsprojectastoplevelelementsinthePackageExplorer.Onlyprojectswhicharepartofthecurrentlyactiveworkingsetsareshown.
Projects Followingactionscanbeusedtoconfiguretheactiveworkingsets:
SelectWorkingSet:OpenstheSelectWorkingSetdialogtoallowselectingtheworkingsetfromwhichelementsshouldbeshown.
DeselectWorkingSet:Deselecttheactiveworkingsets.Allelementsareshownafterinvokingthisaction
EditActiveWorkingSet:OpenstheEditWorkingSetwizardtoeditthecurrentlyactiveworkingset
TopLevelElements> ShowsWorkingSetsastoplevelelementsinthePackageExplorer.
WorkingSets
TheConfigureWorkingSets...actioncanbeusedtoopenadialogwhichallowstoconfigurethevisibleworkingsets.
Filters... OpenstheJavaelementfiltersdialog.
Javaviews
Javaperspectives
Workingsets
Javaelementfiltersdialog
Viewsandeditors
5.8.6.1.JavaElementFiltersDialog
ThisdialogletsyoudefineJavaelementfiltersforthePackageExplorerviewandotherJavaviews.
TheFilterdescriptionfielddisplaysthedescriptionforthecurrentlyselectedfilter.
Filteringelements
PackageExplorerview
5.8.7.VariablesView
TheVariablesViewdisplaysinformationaboutthevariablesassociatedwiththestackframeselectedintheDebugView.WhendebuggingaJavaprogram,variablescanbe
selectedtohavemoredetailedinformationbedisplayedintheDetailPane.Inaddition,Javaobjectscanbeexpandedtoshowthefieldsthatvariablecontains.
TheVariablesView,shownwithcolumns.TheDetailPanetheareaatthebottomoftheviewdisplayingtext.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 249/322
12/10/2015 Javadevelopmentuserguide
TherearemanycommandsavailableintheVariablesView:
ViewDisplayCommandsaffectwhatvariablesaredisplayedandhowtheyarepresented.
TheDetailPanehasmanycommandsavailablebyrightclickingonit.
ViewLayoutCommandsaffecthowthedetailpaneisorientedandwhethercolumnsaredisplayed.
Othercommandsarelistedbelow.
VariablesViewCommands
Context
CopyVariables Copiestheselectedvariablestothesystemclipboard.
menu
Javaviews
Javaperspectives
Suspendingthreads
Evaluatingexpressions
DetailPane
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 250/322
12/10/2015 Javadevelopmentuserguide
ViewDisplayCommands
ViewLayoutCommands
ExpressionsView
5.8.7.9.CreateWatchExpression
SelecttheCreateWatchExpressioncommand[ ]tocreateanewexpressionbasedontheselectedvariableandaddittotheExpressionsView.
Evaluatingexpressions
ExpressionsView
VariablesView
5.8.8.Javaoutline
ThisviewdisplaysanoutlineofthestructureofthecurrentlyactiveJavafileintheeditorarea.
Toolbarbuttons
Command Name Description
GointoTopLevelType Makesthetopleveltypeofthecompilationunitthenewinputforthisview.Packagedeclarationandimportstatementsarenolongershown.
CollapseAll Collapsealltopleveltypes.
Sort Thisoptioncanbetoggledtoeithersorttheoutlineelementsinalphabeticalorderorsequentialorder,asdefinedontheJava>Appearance
>MemberSortOrderpreferencepage.
HideFields Showsorhidesthefields.
HideStaticFieldsand Showsorhidesthestaticfieldsandmethods.
Methods
HideNonPublic Showsorhidesthenonpublicfieldsandmethods.
Members
HideLocalTypes Showsorhidesthelocaltypes.
Javaeditor
Javaviews
FilteringinJavaviews
Javaelementdecorations
SortingelementsinJavaviews
PresentationoptionsforJavaviews
Restoringadeletedworkbenchelement
Settingmethodbreakpoints
Overridemethods
Viewsandeditors
5.8.9.JavaScrapbookPage
ThescrapbookallowsJavaexpressionstoberun,inspected,anddisplayed,underthecontrolofthedebugger.
Note:Contentassist(suchascodeassist)isavailableonscrapbookpages.
JavaScrapbookpagebuttons
RunSnippet Runninganexpressionevaluatesanexpressionbutdoesnotdisplayaresult.
Display Displayingshowstheresultofevaluatinganexpressionasastringinthescrapbookeditor.
Inspect InspectingshowstheresultofevaluatinganexpressionintheExpressionsview.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 251/322
12/10/2015 Javadevelopmentuserguide
Terminate ThiscommandterminatestheJavaVMthatisusedtoevaluateexpressions.
SettheImportDeclarations Thiscommandssetstheimportdeclarationstobeusedforthecontextofevaluatingthecode
Scrapbook
CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Executinganexpression
NewJavascrapbookpagewizard
5.8.10.TypeHierarchyView
Thisviewshowsthehierarchyofatype.TheTypeHierarchyviewconsistsoftwopanes:
TypeHierarchytreepane
Memberlistpane(optional)
TypeHierarchytreepanetoolbarbuttons
Thetypehierarchytreeshowssupertypes,suptypesorbothofagiventypedependingontheselectionmadeinthetoolbar.
PreviousHierarchy Thismenudisplaysahistoryofpreviouslydisplayedtypehierarchies.
Inputs
ShowtheType Thiscommanddisplaysthetypeinitsfullcontext(i.e.,superclassesandsubclasses)intheTypeHierarchyview.Toseeforwhichtypethe
Hierarchy hierarchyisshown,hoverovertheviewtitle(e.g.,"Types").
Showthe ThiscommanddisplaysthesupertypesandthehierarchyofallimplementedinterfacesofthetypeintheTypeHierarchyview.Thetreestartsat
Supertype theselectedtypeanddisplaystheresultoftraversingupthehierarchy.
Hierarchy
Note:Theselectedtypeisalwaysatthetoplevel,intheupperleftcorner.
ShowtheSubtype Thiscommanddisplaysthesubtypesoftheselectedclassand/orallimplementorsoftheinterfaceintheTypeHierarchyview.Thetreestartsat
Hierarchy theselectedtypeanddisplaystheresultoftraversingdownthehierarchy
Note:Theselectedtypeisalwaysatthetoplevel,intheupperleftcorner.
Layout>Hierarchy Hidesthememberlistpane.
ViewOnly
Memberlistpanetoolbarbuttons
Thememberlistpanedisplaysthemembersofthecurrentlyselectedtypeinthetypehierarchytreepane.
LockViewandShowMembersin ShowsthemembersimplementingtheselectedmethodOnlytypesimplementingthemethodareshown.
Hierarchy
Whentheviewislocked,thememberlistpanenolongertrackstheselectioninthehierarchypaneabove.
ShowAllInheritedMembers Showsorhidesallmethodsandfieldsinheritedbybaseclasses.Whenthisoptionisset,thenameofthetypethatdefinesthe
methodisappendedtothemethodname.
SortMembersbytheDefining Sortsthemembersaccordingtothetypeinwhichtheyaredefined.
Type
HideFields Showsorhidesthefields.
HideStaticFieldsandMethods Showsorhidesthestaticfieldsandmethods.
HideNonPublicMembers Showsorhidesthenonpublicfieldsandmethods.
Javaviews
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 252/322
12/10/2015 Javadevelopmentuserguide
Viewsandeditors
5.8.11.CallHierarchyView
TheCallHierarchyviewshowscallersandcalleesforaselectedJavamember.
CallHierarchycommands:
Refresh Refreshthewholehierarchy
Refresh(context Refreshtheselectedelementsandtheirdirectchildren
menu)
CancelCurrentSearch Cancelthecurrentrunningsearch.Usefulforlongrunningsearches.
ShowCallerHierarchy Showallcallersinthesearchscopeoftheselectedmember.
ShowCalleeHierarchy Showallmemberswhicharecalledbythecurrentlyselectedmember.
ShowHistoryList Thismenudisplaysahistoryofpreviouslydisplayedcallhierarchies.
PintheCallHierarchy PinsthecurrentviewandenablestheusertoopenmultipleCallHierarchyviewsatthesametime.
View
Layout Specifiesthelayoutofthecallhierarchyviews
FieldAccesses Specifieswhichfieldaccessestoshow:Readorwriteaccesses,orboth
SearchIn... SpecifieswhereinthescopetheCallHierarchyshouldsearchforresults.
SearchScope Definesthescopeforthesearchforcallers.
Filters Specifiesthepatternswhosematchingmemberswillbehiddenfromtheview.
Expandwith Expandsandreplacesaninstancemethod'snormalchildrenwith:
Constructors(context
menu) theconstructorsofthemethod'sdeclaringclass
anodethatcontainsthedirectcallersofthemethod
Thisisespeciallyusefulformethodsinanonymousclasses.
Expandwith Specifiesthelistoftypeswhoseinstancemethodsareexpandedwithconstructorsbydefault.Thefeaturecanalsobeenabledordisabled
Constructors... forallmethodsdeclaredinanonymoustypesatonceusingtheAllmethodsinanonymoustypesoption.
RemovefromView Removetheselectednodesfromtheview
Javaviews
Viewsandeditors
5.8.12.JUnitView
TheJUnitviewshowsyoutheJUnittestrunprogressandstatus,andallowsyoutoreruntests.
JUnitViewcommands:
NextFailedTest Navigatestothenextfailedtest.
PreviousFailedTest Navigatestothepreviousfailedtest.
ShowFailuresOnly Showsonlyfailedtests.
ScrollLock Changesifscrolllockshouldbeenabledornot.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 253/322
12/10/2015 Javadevelopmentuserguide
RerunTest Rerunthetest.
RerunTestFailuresFirst Rerunthetest,andrunthefailuresfirst.
StopJUnitTestRun StopsthecurrentJUnittestrun.
TestRunHistory Thismenudisplaysahistoryofpreviouslyruntests.
ClearTerminated Clearsalltheterminatedtestrunsfromthehistroy.
Import... ImportsatestrunresultfromaXMLfile.
ImportfromURL... ImportsatestrunresultviaanURL.
ImportURLfromClipboard ImportsatestrunresultviaanURLplacedonclipboard.
Export ExportsthetestrunresulttoaXMLfile.
ShowTestsinHierarchy Showsthetestsinahierarchicallayout.
ShowExecutionTime Showsexecutiontimeforthetests.
Layout SpecifiesthelayoutoftheJUnitview.
ActivateonError/FailureOnly ChangesiftheJUnitviewshouldbeactivatedonlyonerror/failureornot.
Javaviews
Viewsandeditors
5.8.13.JavadocView
TheJavadocviewshowstheJavadocoftheelementselectedintheJavaeditororinaJavaview.
Youcanalsoclickindividualpackagenamesdisplayedintheheadertoseeapackage'sJavadoc.
JavadocViewcommands:
Back Navigatestothepreviouspage.
Forward Navigatestothenextpage.
LinkwithSelection LinkstheJavadocview'sinputwiththeselectionintheJavaeditororinaJavaview.
LinkwithSelection(showinglastvalidinput) IndicatesthattheJavadocview'scontentisnolongerinsyncwiththecurrentselection.
OpenInput OpensthecurrentinputelementoftheJavadocviewintheJavaeditor.
OpenAttachedJavadocinaBrowser(Shift+F2) OpenstheattachedjavadocofcurrentinputoftheJavadocviewinabrowser.
Javaviews
Viewsandeditors
5.9.1.Content/CodeAssist
IntheJavaeditorpressCtrl+Spaceoncodetocomplete.Thisopensalistofavailablecodecompletions.Sometipsforusingcodeassistarelistedinthefollowingparagraph:
Youcanusethemouseorthekeyboard(UpArrow,DownArrow,PageUp,PageDown,Home,End,Enter)tonavigateandselectlinesinthelist.
Ifyouselectalineinthecontentassistlist,youcanviewJavadocinformationforthatline.
ClickingorpressingEnteronaselectedlineinthelistinsertstheselectionintotheeditor.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 254/322
12/10/2015 Javadevelopmentuserguide
YoucanaccessspecializedcontentassistfeaturesinsideJavadoccomments.
ConfigurethebehaviorofthecontentassistintheJava>Editor>CodeAssistpreferencepage.
Javaeditor
Javadevelopmenttools(JDT)
Editmenu
Javaeditorpreferences
Templatespreferences
5.9.2.Formatter
IntheJavaeditorpressCtrl+Shift+Foncodetoformatit.Ifnoselectionissetthentheentiresourceisformattedotherwiseonlytheselectionwillbe.Sometipsforusingthe
formatterarelistedintheparagraphsofthischapter.
NotethattheJavaFormatterpreferencesareaccessibleonthe JavaFormatterpreferencepage.
Disablingformatterinsidesections
Youcandisable/enabletheformatterinoneorseveralsectionsinthecodeasshowninthesamplebelow:
Thesnippetaboveusedefaulttagnames,buttheycanbechangedontheOff/OntagstaboftheJavaFormatterpreferencepage.
Wrapoutermostmethodcalls
Sinceversion3.6,theJavaformatternowtriestowraptheoutermostmethodcallsfirsttohaveabetteroutputwhenwrappingnestedmethodcalls.
Hereisanexampleofaformattedcodewheretheformatterhaswrappedthelinebetweentheargumentsoftheoutermostmessagecalltokeepeachnestedmethodcallonasingle
line:
Anewpreferenceallowsyoutodisablethisstrategy,typicallyifyouwanttoformatyourcodeasbefore,thenuncheckthePreferwrappingouterexpressionspreference
accessibleontheLinewrappingtaboftheJavaFormatterpreferencepage.
Note:Currentlythenewstrategyonlyappliestonestedmethodcalls,butthatmightbeextendedtoothernestedexpressionsinfutureversions.
CondenseJavadocandblockcomments
Userscanreducethenumberoflinesofformattedmultilinescommentsasshownintheexamplebelow:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 255/322
12/10/2015 Javadevelopmentuserguide
Toactivatethisbehavioruncheckthe/*and*/onseparatelinespreferenceaccessibleontheCommentstaboftheJavaFormatterpreferencepage.
ThesamekindofpreferenceisalsoavailablefortheJavadoccomments.
Preserveuserlinebreaks
Userscanpreservelinebreaksbynotjoininglinesincodeorcomments.
Forexample,thealreadywrappedlinesofthereturnstatementinthefollowingtestcase:
willbepreservedbytheformatterwhentheNeverjoinlinespreferenceisused,henceproducesthefollowingoutputwhenformatted:
ToactivatethisbehaviorchecktheNeverjoinlinespreferenceaccessibleontheLineWrappingandtheCommentstabsoftheJavaFormatterpreferencepage.
Javaeditor
Javadevelopmenttools(JDT)
Editmenu
Javaeditorpreferences
Formatterpreferences
5.9.3.QuickFix
TheJavaeditorofferscorrectionstoproblemsfoundwhiletypingandaftercompiling.Toshowthatcorrectionproposalsareavailableforaproblemorwarning,a'lightbulb'isvisible
ontheeditor'sannotationbar.
LeftclickonthelightbulborinvokingCtrl+1(Edit>QuickFix)bringsuptheproposalsfortheproblematthecursorposition.
Eachquickfixshowsapreviewwhenselectedintheproposalwindow.
Quickfixesarealsoshowndirectlyinproblemhovers(butthere,nopreviewisavailable).
Usagehint:Quickfixesarenotonlyusefultofixerrorsthataccidentallyoccurred.Anothercommonusagepatternistoinentionallywrite"incorrect"code,forexamplebyreferringto
alocalvariablethatisnotdeclaredyet.Then,theCreatelocalvariableQuickFixcangeneratethedeclarationinnotime,anditcaneveninferthevariabletype.
Someselectedquickfixescanalsobeassignedwithdirectshortcuts.Youcanconfiguretheseshortcutsonthe General>Keyspreferencepage(inthe'Source'category).
Somequickfixesoffertofixallproblemsofthesamekindinthecurrentfileatonce.Theinformationtextintheproposalwindowcontainsthisinformationforallapplicableproposals.
Tofixallproblemsofthesamekind,pressCtrl+Enter.
Here'saselectionofavailablequickfixes:
PackageDeclaration
Addmissingpackagedeclarationorcorrectpackagedeclaration
Movecompilationunittopackagethatcorrespondstothepackagedeclaration
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 256/322
12/10/2015 Javadevelopmentuserguide
Imports
Removeunused,unresolvableornonvisibleimport
Invoke'Organizeimports'onproblemsinimports
Types
Createnewclass,interface,enum,annotationortypevariableforreferencestotypes
thatcannotberesolved
Changevisibilityfortypesthatareaccessedbutnotvisible
Renametoasimilartypeforreferencestotypesthatcannotberesolved
Addimportstatementfortypesthatcannotberesolvedbutexistintheproject
Addexplicitimportstatementforambiguoustypereferences(twoimportondemandsfor
thesametype)
Ifthetypenameisnotmatchingwiththecompilationunitnameeitherrenamethetypeor
renamethecompilationunit
Removeunusedprivatetypes
Addmissingtypeannotationattributes
Constructors
Createnewconstructorforreferencestoconstructorsthatcannotberesolved(this,
superornewclasscreation)
Reorder,addorremoveargumentsforconstructorreferencesthatmismatchparameters
Changemethodwithconstructornametoconstructor(removereturntype)
Changevisibilityforconstructorsthatareaccessedbutnotvisible
Removeunusedprivateconstructor
Createconstructorwhensupercalloftheimplicitdefaultconstructorisundefined,not
visibleorthrowsanexception
Iftypecontainsunimplementedmethods,changetypemodifierto'abstract'oraddthe
methodtoimplement
Methods
Createnewmethodforreferencestomethodsthatcannotberesolved
Renametoasimilarmethodforreferencestomethodsthatcannotberesolved
Reorderorremoveargumentsformethodreferencesthatmismatchparameters
Correctaccess(visibility,static)ofreferencedmethods
Removeunusedprivatemethods
Correctreturntypeformethodsthathaveamissingreturntypeorwherethereturntype
doesnotmatchthereturnstatement
Addreturnstatementifmissing
Fornonabstractmethodswithnobodychangeto'abstract'oraddbody
Foranabstractmethodinanonabstracttyperemoveabstractmodifierofthemethodor
maketypeabstract
Foranabstract/nativemethodwithbodyremovetheabstractornativemodifierorremove
body
Changemethodaccessto'static'ifmethodisinvokedinsideaconstructorinvocation
(super,this)
Changemethodaccesstodefaultaccesstoavoidemulatedmethodaccess
Add'synchronized'modifier
OverridehashCode()
Openthe'GeneratehashCode()andequals()'wizard
Fieldsandvariables
Correctaccess(visibility,static)ofreferencedfields
Createnewfields,parameters,localvariablesorconstantsforreferencestovariables
thatcannotberesolved
Renametoavariablewithsimilarnameforreferencesthatcannotberesolved
Removeunusedprivatefields
Correctnonstaticaccessofstaticfields
Add'final'modifiertolocalvariablesaccessedinoutertypes
Changefieldaccesstodefaultaccesstoavoidemulatedmethodaccess
Changelocalvariabletypetofixatypemismatch
Initializeavariablethathasnotbeeninitialized
Creategetterandsettersforinvisibleorunusedfields
Createloopvariabletocorrectanincompleteenhanced'for'loopbyaddingthetypeof
theloopvariable
ExceptionHandling
Removeunneededcatchblock
Removeunneededexceptionsfromamulticatchclause(1.7orhigher)
Handleuncaughtexceptionbysurroundingwithtry/catchoraddingcatchblocktoa
surroundingtryblock
Handleuncaughtexceptionsbysurroundingwithtry/multicatchoraddingexceptionsto
existingcatchclause(1.7orhigher)
Handleuncaughtexceptionbyaddingathrowdeclarationtotheparentmethodorby
generalizeanexistingthrowdeclaration
BuildPathProblems
AddamissingJARorlibraryforanunresolvabletype
Openthebuildpathdialogforaccessrestrictionproblemsormissingbinaryclasses.
ChangeprojectcomplianceandJREto1.5
ChangeworkspacecomplianceandJREto1.5
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 257/322
12/10/2015 Javadevelopmentuserguide
Others
Addcastorchangecasttofixtypemismatches
Letatypeimplementaninterfacetofixtypemismatches
Addtypeargumentstorawreferences
Completeswitchstatementsoverenums
Removedeadcode
Insert'//$FALLTHROUGH$'
Insertnullcheck
FornonNLSstringsopentheNLSwizardormarkasnonNLS
Addmissing@Override,@Deprecatedannotations
AddmissingJavadoccomments
AddmissingJavadoctags
Suppressawarningusing@SuppressWarnings
Throwtheallocatedobject
Returntheallocatedobject
Add@SafeVarargsannotationforheappollutionwarnings(1.7orhigher)
Removeinvalid@SafeVarargsannotations(1.7orhigher)
Removeredundanttypearguments(1.7orhigher)
Addinferredtypearguments(1.5and1.6)
Removeunusedtypeparameter(1.5orhigher)
QuickAssistsareproposalsavailableevenifthereisnoproblemorwarning.SeetheQuickAssistpageformoreinformation.
Javaeditor
Quickfixandassist
QuickAssist
JDTactions
5.9.4.QuickAssist
Quickassistsperformlocalcodetransformations.TheyareinvokedonaselectionorasinglecursorintheJavaeditorandusethesameshortcutasquickfixes(Ctrl+1),butquick
assistareusuallyhiddenwhenanerrorisaround.Toshowthemevenwitherrorspresentonthesameline,pressCtrl+1asecondtime.
Aselectionofquickassistscanbeassignedtoadirectshortcut.Bydefault,theseare:
Renameinfile:Ctrl+2,R
Assigntolocal:Ctrl+2,L
Assigntofield:Ctrl+2,F
Assignmoreshortcutsorchangethedefaultshortcutsonthe General>Keyspreferencepage(inthe'Source'category).
Aquickassistlightbulbcanbeturnedononthe Java>Editorpreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 258/322
12/10/2015 Javadevelopmentuserguide
Splitifstatementwith if(a&&b){} > if(a){if(b){}} Onanand'edexpression
and'edexpression ina'if'
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 259/322
12/10/2015 Javadevelopmentuserguide
Extracttolocal foo(getColor()) > Colorcolor=getColor() Onanexpression
foo(color)
Createmethodinsuper Onamethoddeclaration
class
Renameinfile Onidentifiers
Renameinworkspace Onidentifiers
ThefollowingquickassistsareavailableinthePropertiesFileEditor:
Renameinworkspacerenamesthekeyinthepropertiesfileandupdatesallreferences
Createfieldin'...'createsthecorrespondingfieldintheresourcebundleaccessorclass
Removepropertydeletesthepropertyfromthepropertiesfileandthefieldfromtheresourcebundleaccessorclass
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 260/322
12/10/2015 Javadevelopmentuserguide
Removepropertiesdeletestheselectedpropertiesfromthepropertiesfileandthefieldsfromtheresourcebundleaccessorclass
Escapebackslashesescapeallbackslashesintheselectedtext
Escapebackslashesinoriginalstringescapeallbackslashesinthepastedtext
Unescapebackslashesunescapeallbackslashesintheselectedtext
JavaEditor
QuickFixandQuickAssist
QuickFix
JDTactions
5.10.1.1.NewJavaProjectWizard
The NewJavaProjectwizardhelpsyoucreateanewJavaprojectintheworkbench.
Projectnamepage
Option Description Default
Project Typeanameforthenewproject. <blank>
name
Location When'Usedefaultlocation'isselected,theNewProjectWizardwillcreateanewprojectwiththespecifiednameintheworkspace. workspace
Otherwise,youcanspecifythelocationfromwhichtheNewJavaProjectWizardwillretrieveanexistingJavaproject.Inthiscasethe
wizardwillanalyzetheexistingprojectandsetupthebuildpathautomatically.ClickonBrowse...tobrowseforalocationofanexisting
Javaproject.
JRE UsedefaultJRE
UsedefaultJRE:
Whenselected,theNewJavaProjectWizardcreatesanewJavaprojectwhichusestheworkspacedefaultJRE.Thedefault
JREcanbeconfiguredontheJava>InstalledJREspreferencepage.
TheprojectwillalsousethedefaultcompilercompliancewhichcanbeconfiguredontheJava>Compilerpreferencepage.
ClickonConfiguredefault...toconfigurethedefaultJREandcompilercompliance.
UseprojectspecificJRE:
Whenselected,youcanexplicitlyspecifytheJREtobeusedforthenewJavaproject.Thenewprojectwilluseacompiler
compliancewhichmatchestheversionoftheselectedJRE.
UseanexecutionenvironmentJRE:
Whenselected,youcanspecifyanexecutionenvironmenttobeusedforthenewJavaproject.Thenewprojectwillusea
compilercompliancewhichfitsbesttheselectedexecutionenvironment.
ExecutionenvironmentscanbeconfiguredontheJava>InstalledJREs>ExecutionEnvironmentspreferencepage.
Project Createseparatefoldersfor
layout Useprojectfolderasrootforsourcesandclassfiles: sourcesandclassfiles
Whenselected,theprojectfolderisusedbothassourcefolderandasoutputfolderforclassfiles.
Createseparatefoldersforsourcesandclassfiles:
Whenselected,theNewJavaProjectWizardcreatesasourcefolderforJavasourcefilesandanoutputfolderwhichholdsthe
classfilesoftheproject.
Working Dependsonthecontextfrom
sets Addprojecttoworkingsets: whichthewizardhasbeen
Whenselected,thenewprojectwillbeaddedtotheworkingsetsshowninWorkingSetsdropdownfield.Thedropdownfield started
showsalistofpreviousselectedworkingsets.
ClickonSelect...toselectworkingsetstowhichtoaddthenewproject.
JavaBuildPathpage
YoucanskipthispagebypressingFinishonthefirstpage.OtherwisepressNexttoconfiguretheJavabuildpath.
TheJavabuildpathconsistofsource,libraryandprojectentries.TheuserinterfaceisthesameasfortheBuildPathpropertypage,exceptforthesourcetab:
Sourcetab
Sourcefoldersaretoplevelfoldersintheprojecthierarchy.Theyaretherootofpackagescontaining.javafiles.Thecompilerwilltranslatethecontainedfilesto.classfilesthatwill
bewrittentotheoutputfolder.
Sourcefoldersallowtostructuretheproject,forexampletoseparatetestfromtheapplicationintwosourcefolders.Withinasourcefolder,amoredetailedstructuringcanbe
achievedbyusingpackages.
Eachsourcefoldercandefineanexclusionfiltertospecifywhichresourcesinsidethefoldershouldnotbevisibletothecompiler.
ResourcesexistinginsourcefoldersarecopiedtotheoutputfolderunlessthesettingintheJava>Compiler>Buildingpreferencepagespecifiesthattheresourceisfiltered.The
outputfolderisdefinedperprojectexceptifasourcefolderspecifiesitsownoutputfolder.
Thetreeshowstheprojectasitwilllooklikewhenswitchingtothepackageexplorer.Severaloperationscanbeexecutedonthistreetochangethestructureoftheproject.
Addsourcefolder AddafoldertotheJavabuildpathassourcefolder.
Linkadditional AddalinktoafolderinthefilesystemassourcefoldertotheJavabuild
sourcetoproject path.
Removefrom RemoveasourcefolderfromtheJavabuildpathandchangeitintoa
buildpath normalfolder.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 261/322
12/10/2015 Javadevelopmentuserguide
Addaresourcetotheexclusionfilterofitsparentsourcefolder.The
Exclude
excludedresourceandallitschildrenarenolongervisibletothecompiler.
Include Includesapreviouslyexcludedresource.
Theeditsourcefolderpropertymenuhastwoactions
1. ConfigureInclusion/ExclusionsFilters:Customizethe
inclusionandexclusionfiltersbydefiningstringpatterns.Itis
Configuresource possibletousewildcardinpatters(i.e.toexcludealljavafiles
folderproperties whichstartwith"Test"write"Test*.java").
2. ConfigureOutputFolder:Changetheoutputfolderforasource
folder.ThisactionisonlyenabledifAllowoutputfoldersfor
sourcefoldersisenabled.
Allchangesthathavebeenappliedtotheprojectinthiswizardwillbe
Undoallchanges
withdrawnandtheoriginalstateoftheprojectisreconstructed.
Allowoutput Ifenabled,eachsourcefoldercanhaveitsownoutputfolder.Otherwise
foldersforsource allsourcefolderswillusethedefaultoutputfolder.
folders
AshorterdescriptionofalloperationsisvisibleintheDetailspanebelowtheprojecttree.
Librarytab,ProjecttabandOrderTab
SeeBuildPathpropertypageformoredetails.
Javaprojects
Fileactions
5.10.1.2.NewJavaPackageWizard
The NewJavaPackagewizardhelpsyoucreateafoldercorrespondingtoanewJavapackageandoptionallyapackageleveldocumentationfile.Itcanalsobeusedtoadd
packageleveldocumentationtoanexistingpackage.
Thecorrespondingfolderofthedefaultpackagealwaysexists,andthereforedoesn'thavetobecreated.
JavaPackageOptions
Option Description Default
Sourcefolder Typeorbrowsetoselectacontainer(projectorfolder)forthenewpackage. Thesourcefolderoftheelementthatwasselected
whenthewizardhasbeenstarted.
Name Typeanameforthenewpackage Theprojectname,ifitisavalidpackagenameand
ifthesourcefolderdoesnotcontainanyother
package,otherwise<blank>
Createpackage false
info.java Whetherapackageinfo.javafileshouldbecreatedinthepackage.
Thepackageinfo.javafilecontainspackageleveldocumentationaswellasannotations.Forexample:
/**
*ThispackagecontainsJAXBclasses.
*/
@XmlSchema(namespace="http://www.example.com",elementFormDefault=XmlNsForm.QUALIFIED)
packagecom.acme.jaxb
Formoreinformation,refertotheJavaLanguageSpecificationSection7.4.1.NamedPackages.
Ifthesourcelevelis1.4orbelow,apackage.htmlwillbecreatedinstead.
Fileactions
5.10.1.3.NewJavaClassWizard
The NewJavaClasswizardhelpsyoutocreateanewJavaclassinaJavaproject.
JavaClassOptions
Option Description Default
Sourcefolder Enterasourcefolderforthenewclass.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewclass.Youcanselecteitherthis Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
optionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type class.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselect
atypeviaadialog.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 262/322
12/10/2015 Javadevelopmentuserguide
Modifiers public
Selectoneormoreaccessmodifiersforthenewclass.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
abstract
final
static(onlyavailableifyouspecifyanenclosingtype)
Fileactions
5.10.1.4.NewJavaEnumWizard
The NewJavaEnumTypewizardhelpsyoutocreateanewJavaenuminaJavaproject.
JavaEnumOptions
Option Description Default
Source Enterasourcefolderforthenewenum.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewenum.Youcanselecteitherthis Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
optionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenewenum. Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type YoucanselecteitherthisoptionorthePackageoption,above.Either beenstartedor<blank>
typeavalidnameinthefieldorclickBrowsetoselectatypeviaa
dialog.
Name Typeanameforthenewenum. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewenum.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
Fileactions
5.10.1.5.NewJavaInterfaceWizard
The NewJavaInterfacewizardhelpsyoutocreateanewJavainterfaceinaJavaproject.
JavaInterfaceOptions
Option Description Default
Source Enterasourcefolderforthenewinterface.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewinterface.Youcanselecteither Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
thisoptionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type interface.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselecta
typeviaadialog.
Name Typeanameforthenewinterface. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewinterface.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 263/322
12/10/2015 Javadevelopmentuserguide
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
static(onlyavailableifyouspecifyanenclosingtype)
Fileactions
5.10.1.6.NewJavaAnnotationWizard
The NewJavaAnnotationTypewizardhelpsyoutocreateanewJavaAnnotationinaJavaproject.
JavaAnnotationOptions
Option Description Default
Source Enterasourcefolderforthenewannotation.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewannotation.Youcanselecteither Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
thisoptionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type annotation.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselecta
typeviaadialog.
Name Typeanameforthenewannotation. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewannotation.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
Fileactions
5.10.1.7.NewSourceFolderWizard
The NewSourceFolderwizardhelpsyoutocreateanewsourcefoldertoaJavaproject.
Notethatanewsourcefoldercannotbenestedinexistingsourcefoldersorinanoutputfolder.Youcanchoosetoaddexclusionfilterstotheothernestingsourcefoldersorthe
wizardwillsuggesttoreplacethenestingclasspathentrywiththenewcreatedentry.Thewizardwillalsosuggesttochangetheoutputlocation.
NewSourceFolderOptions
Option Description Default
Projectname Enteraprojecttocontainthenewsourcefolder.EithertypeavalidprojectnameorclickBrowsetoselecta Theprojectoftheelementthatwas
projectviaadialog. selectedwhenthewizardhasbeen
started.
Foldername Typeapathforthenewsourcefolder.Thepathisrelativetotheselectedproject. <blank>
Updateexclusionfilterin Selecttomodifyexistingsourcefolder'sexclusionfilterstosolvenestingproblems.Forexampleifthereisan Off
othersourcefoldersto existingsourcefoldersrcandafoldersrc/inneriscreated,thesourcefoldersrcwillbeupdatedtohavea
solvenesting exclusionfiltersrc/inner.
Javaprojects
Fileactions
5.10.1.8.NewJavaScrapbookPageWizard
The NewJavaScrapbookPagewizardhelpsyoutocreateanewJavascrapbookpageinaproject.
CreateJavaScrapbookPageOptions
Option Description Default
Enterorselecttheparentfolder Typeorbrowsethehierarchybelowtoselectacontainer(projectorfolder)forthescrapbookpage. Thecontaineroftheselectedelement
Filename Typeanameforthenewfile.The".jpage"extensionisappendedautomaticallywhennotaddedalready. <blank>
Javascrapbookpage
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 264/322
12/10/2015
Fileactions
Javadevelopmentuserguide
5.10.2.ExportBreakpointsWizard
The ExportBreakpointswizardhelpsyoutoexportbreakpointstoafile.
Exportbreakpointspage
Option Description Default
Breakpoint Selectthebreakpointsthatyouwishtoexport,anddeselectthosethatyoudo
List not. Therecanbetwopossibledefaults:
Ifthewizardisinvokedfromthebreakpointsviewandanybreakpointsareselected,
thosesameoneswillbecheckedbydefault.
IfthewizardisinvokedviatheFilemenuthannothingwillbeselected.
ToFile Thefiletoexportthebreakpointsto,youcanalsoclickBrowse...tosearchfor
alocationtoexportto. Therecanbetwopossibledefaults:
Ifyouhaveneverexportedbreakpointsbeforeitwillbeblank
Ifyouhaveexportedbreakpointsbeforethelastfilenameyouexportedtowillbe
automaticallyinserted.
Overwrite notselected
Overwriteexistingfilewithoutwarning:
Whenselected,ifthefileyouwishtoexporttoalreadyexists,itwillbe
overwrittenautomaticallybythewizard.
Breakpoints
AddingLineBreakpoints
RemovingLineBreakpoints
LaunchingaJavaProgram
RunningandDebugging
Fileactions
ImportingBreakpoints
5.10.3.ExportLaunchConfigurationsWizard
The ExportLaunchConfigurationswizardhelpsyoutoexportbreakpointstoafile.
Exportlaunchconfigurationspage
Option Description Default
Launchconfigurationlist Selectthelaunchconfigurationsthatyouwishtoexport,anddeselectthosethatyoudonot. None
SelectAll Canbeusedtoquicklyselectalllaunchconfigurationsinthelist. None
DeselectAll Canbeusedtoquicklydeselectalllaunchconfigurationsinthelist. None
Location Thefoldertoexportthelaunchconfigurationsto. None
Browse... TheBrowse...buttonallowsyoutosearchforaspecificfoldertoexportlaunchconfigurationsto. None
Overwriteexistingfile(s)without Whenselected,ifthelocationalreadycontainsalaunchconfigurationbeingexported,itwillbeoverwrittenautomaticallyby Not
warning thewizard. Selected
LaunchingaJavaProgram
RunningandDebugging
Fileactions
ImportingLaunchConfigurations
5.10.4.ExternalizeStringsWizard
TheExternalizeStringswizardallowsyoutorefactoracompilationunitsuchthatstringsusedinthecompilationunitcanbetranslatedtodifferentlanguages.Thewizardcanbe
invokedonnew,unprocessedfiles,butalsomodifyalreadytranslatedpages.Italsoallowsyourevertchangesdonebyapreviousinvocationofthewizard.
Onthefirstpageofthewizardyoucanspecifyhowthestringsfoundinthecompilationunitshouldbeexternalized.Itisalsopossibletointernalizestringswhichhavebeen
externalizedbefore.
Field Description
UseEclipse'sstring Ifuncheckedthestandardexternalizationmechanismisused,otherwisethenewEclipsestringexternalizationmechanismisused.
externalizationmechanism Note:Thisfieldisonlypresentiftheprojectbuildpathcontainstheorg.eclipse.osgi.util.NLSclass.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 265/322
12/10/2015 Javadevelopmentuserguide
Entercommonprefixfor Specifiesanoptionalprefixforallnewlygeneratedkey.Agoodpracticeistousethenameofthecompilationunitsoentriesinthepropertyfilescan
generatedkeys easilybegrouped.
Stringstoexternalize Displaysthelistofallstringsinthefile.Whennonexternalizedstringsarefound,thelistillbefilteredtoonlyshowthenewstringswithproposed
keysandvalues.Tocontrolthisfilter,usethecheckboxontopofthetable.
Externalize Markstheselectedstringstobeexternalized.Externalizedstringswillbeplacedinapropertyfileandthecodewillbechangedtoalookuptothe
propertyfile.
Ignored Markstheselectedstringstobeignoredfromexternalization.Thesestringswillbemarkedwitha'//$NON_NLS'commentandthecompilerwill
ignorethisstringwhenwarningaboutnonexternalizedstrings.
Internalize Markstheselectedstringstobeinternalizedagain:Thisbringsthecodebackinitsoriginalstatebeforetheexternalizewizardwasapplied:The
entryinthepropertyfilewillberemoved,anda'//$NON_NLS'commentwillberemoved.
Edit... Opensadialogforenteringanewkey.
Context Displaystheoccurrenceofthestringinthecontextofthecompilationunit.
Accessorclass Theclassusedtoaccessthepropertyfile.PressConfigure...toopentheConfigureAccessorClassdialog.
ConfigureAccessorClass
Thisdialogspecifiesthenameandlocationofthepropertyfileanditsaccessorclass.Anaccessorclassisusedtoretrievestringsstoredinthepropertyfilegivenakey.
Accessorclasssettings:
Option Description
Sourcefolder Thesourcefoldertostoretheaccessorclassin.
Package Thelocationfortheaccessorclass.
Classname Thenameoftheclasstoaccesstheresourcebundle.
Substitutionpattern Specifiesthesourcepatterntoreplacethestringtoexternalizewith.
Propertyfilesettings:
Option Description
Sourcefolder Thesourcefoldertostorethepropertyfilein.
Package Thelocationforthepropertyfile.
Propertyfilename Thenameofthepropertyfile.
Stringexternalization
Eclipsestringexternalizationmechanism
Externalizingstrings
Sourceactions
5.10.5.ImportBreakpointsWizard
The ImportBreakpointswizardhelpsyoutoimportbreakpointsfromafile.
Importbreakpointspage
Option Description Default
From... Typethenameofthefiletoimportfrom,orclicktheBrowse...buttontosearchforafile. <blank>
Update... not
Automaticallyupdateexistingbreakpoints selected
Whenselected,anybreakpointsthatalreadyexistinyourworkspacewillbeoverwrittenbythosebeingimportedfromthefile.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 266/322
12/10/2015 Javadevelopmentuserguide
Create... not
Automaticallycreatebreakpointsworkingsets: selected
Whenselected,ifanimportedbreakpointindicatesitbelongstoaworkingsetsthatdoesnotexistinyourworkspace,theworkingsetwillbecreated
foryouandthebreakpointaddedtoit.
Breakpoints
AddingLineBreakpoints
RemovingLineBreakpoints
LaunchingaJavaProgram
RunningandDebugging
Fileactions
ExportingBreakpoints
5.10.6.ImportLaunchConfigurationsWizard
The ImportLaunchConfigurationswizardhelpsyoutoimportbreakpointsfromafile.
Importlaunchconfigurationspage
Option Description Default
FromDirectory Thefoldertoimportlaunchconfigurationsfrom. None
Browse... TheBrowse...buttonallowsyoutosearchforaspecificfoldertoimportlaunchconfigurationsfrom. None
Overwriteexistinglaunchconfigurationswithout Whenselected,anylaunchconfigurationsthatalreadyexistinyourworkspacewillbeoverwrittenbythosebeing Not
warning imported. Selected
LaunchingaJavaProgram
RunningandDebugging
Fileactions
ExportingLaunchConfigurations
5.10.7.JARFileExporter
The JarExportwizardallowsyoutocreateaJARfile.
JARpackagespecification
JARSpecificationOptions:
Option Description
Selecttheresourcestoexport Inthelist,checkorcleartheboxestospecifyexactlythefilesthatyouwanttoexporttotheJARfile.Thislistisinitializedbytheworkbench
selection.
Exportgeneratedclassfiles Ifenabled,thengeneratedclassfilesandresourcesareincludedintheJAR.
andresources
Exportalloutputfoldersfor Ifenabled,thenalloutputfoldersareincludedintheJAR.
checkedprojects
ExportJavasourcefilesand Ifenabled,thenJavasourcefilesandresourcesareincludedintheJAR.
resources
Exportrefactoringsforchecked Ifenabled,thenrefactoringscriptsfortheselectedprojectsareincludedintheJAR.ThisallowsclientstomigratetothenewJARbyexecutingall
projects thestoredrefactoringsintheJAR.
Selecttheexportdestination EnteranexternalfilesystempathandnameforaJARfile(eitherneworexisting).EithertypeavalidfilepathinthefieldorclickBrowsetoselect
afileviaadialog.
Options Youcanselectanyofthefollowingoptions:
CompressthecontentsoftheJARfile:tocreateacompressedJARfile
Adddirectoryentries:addsanentryforeachdirectorytotheJARfile,evenifthedirectorydoesonlycontainsubdirectories.
Overwriteexistingfileswithoutwarning:ifanexistingfilemightbeoverwritten,youarepromptedforconfirmation.Thisoptionisapplied
totheJARfile,theJARdescription,andthemanifestfile.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 267/322
12/10/2015 Javadevelopmentuserguide
JARpackagingoptions
JAROptions:
Option Description
Selectoptionsforhandlingproblems Choosewhethertoexportclasseswithcertainproblems:
Exportclassfileswithcompileerrors
Exportclassfileswithcompilewarnings
SelectedthisoptionifyouwantthesourcefolderstructuretoberebuiltintheJAR.Thisoptionisonlyenabledwhensourcefilesbutno
Createsourcefolderstructure
classfilesareexported.
Selectthisoptiontoforcearebuildbeforeexporting.Itisrecommendedtobuildbebeforeexportingsotheexportedclassfilesareupto
Buildprojectsifnotbuildautomatically
date.
SavethedescriptionofthisJARinthe Ifyouselectthisoption,youcancreateafileintheworkbenchdescribingtheJARfileyouarecreating.Eithertypeand/orbrowseto
workspace selectapathandnameforthisnewfile.
JARmanifestspecification
JARManifestSpecificationOptions(Availablewhenclassfileareexported):
Option Description
Specifythemanifest ChoosethesourceofthemanifestfileforthisJARfile:
Generatethemanifestfile(youcanalsochooseeithertosaveorreuseandsavethenewmanifestfile)
Useexistingmanifestfromworkspace
Sealcontents ChoosewhichpackagesintheJARfilemustbesealed:
SealtheJARtosealtheentireJARfileclickDetailstoexcludeselectively
SealsomepackagesclickDetailstochooseselectively
Note:Thisoptionisonlyavailableifthemanifestisgenerated.
Selecttheclassoftheapplicationentrypoint TypeorclickBrowsetoselectthemainclassfortheJARfile,ifdesired.
Note:Thisoptionisonlyavailableifthemanifestisgenerated.
CreatingJARfiles
Fileactions
5.10.8.JavadocGeneration
The JavadocGenerationwizardallowsyoutogenerateJavadoc.Itisauserinterfaceforthejavadoc.exetoolavailableintheJavaJDK.VisitSun'sJavadocToolpagefora
completedocumentationoftheJavadoctool.
Firstpage
TypeSelection:
Option Description
Javadoccommand Specifywhichcommandtousetogeneratethejavadoc.
SelecttypesforwhichJavadoc Inthelist,checkorcleartheboxestospecifyexactlythetypesthatyouwanttoexport.Thislistisinitializedbytheworkbenchselection.
willbegenerated
CreateJavadocformembers Private:Allmemberswillbedocumented
withvisibility Package:Onlymemberswithpackage,protectedorpublicvisibilitywillbedocumented
Protected:Onlymemberswithprotectedorpublicvisibilitywillbedocumented
Public:Onlymemberswithpublicvisibilitywillbedocumented(default)
Usestandarddoclet StarttheJavadoccommandwiththestandarddoclet(default)
Destination:selectthedestinationtowhichthestandarddocletwillwritethegenerateddocumentation.Thedestinationisadocletspecific
argument,andthereforenotenabledwhenusingacustomdoclet.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 268/322
12/10/2015 Javadevelopmentuserguide
Usecustomdoclet Useacustomdoclettogeneratedocumentation
Docletname:Qualifiedtypenameofthedoclet
Docletclasspath:Classpathneededbythedocletclass
Standarddocletarguments
StandardDocletArguments(availablewhenUsestandarddoclethasbeenselected):
Option Description
Specifyadocumenttitle.
Documenttitle
Generateusepage SelectedthisoptionifyouwantthedocumentationtocontainaUsepage.
Generatehierarchytree SelectedthisoptionifyouwantthedocumentationtocontainaTreepage.
Selectedthisoptionifyouwantthedocumentationtocontainanavigationbar(headerandfooter).
Generatenavigatorbar
Generateindex SelectedthisoptionifyouwantthedocumentationtocontainaIndexpage.
Separateindexperletter Createanindexperletter.EnabledwhenGenerateIndexisselected.
@author Selectedthisoptionifyouwanttothe@authortagtobedocumented.
@version Selectedthisoptionifyouwanttothe@versiontagtobedocumented.
@deprecated Selectedthisoptionifyouwanttothe@deprecatedtagtobedocumented.
SelectedthisoptionifyouwantthedocumentationtocontainaDeprecatedpage.Enabledwhen
deprecatedlist
the@deprecatedoptionisselected.
SpecifytowhichotherdocumentationJavadocshouldcreatelinkswhenothertypesarereferenced.
Selectreferencedarchivesandprojectstowhichlinksshould SelectAll:Createlinkstoallotherdocumentationlocations
begenerated ClearAll:Donotcreatelinkstootherdocumentationlocations
Configure:ConfiguretheJavadoclocationofareferencedJARorproject.
Stylesheet Selectthestylesheettouse
Generalarguments
GeneralJavadocOptions:
Option Description
SpecifiesthatJavadocshouldretrievethetextfortheoverviewdocumentationfromthegivenfile.Itwillbeplacedinoverviewsummary.html.
Overview
VMoptions AddanynumberofextraVMoptionshere.
ExtraJavadocoptions Addanynumberofextraoptionshere:CustomdocletoptionsorJRE1.4compatibilityoptions.
Notethatargumentscontainingspacesmustenclosedinquotes.Forargumentsspecifyinghtmlcode(e.g.header)usethe&or&"toavoid
spacesandquotes.
JREsourcecompatibility TheJREsourcecompatibilitytobeacceptedbythejavadoctool.
Savethesettingsofthis SpecifytostoreanAntscriptthatwillperformthespecifiedJavadocexportwithouttheneedtousethewizard.ExistingAntscriptcanbe
JavadocexportasanAntscript modifiedwiththiswizard(UseOpenJavadocwizard'fromthecontextmenuonthegeneratedAntscript)
Opengeneratedindexfilein
Opensthegeneratedindex.htmlfileinthebrowser(Onlyavailablewhenusingthestandarddoclet)
browser
PressFinishtostarttheJavadocgeneration.Ifthedestinationisdifferenttothelocationconfiguredtheproject'sJavadocLocationpage,youwillbeaskedifyouwanttosetthe
project'sJavadoclocationtothenewdestinationfolder.Bydoingthis,allinvocationsofOpenExternalJavadocwillusethenowcreateddocumentation.
Anewprocesswillbestartedandthegenerationperformedinthebackground.OpentheConsoleview(Window>ShowView>Console)toseetheprogressandstatusofthe
generation.
Fileactions
Javadoclocationproperties
5.10.9.RunnableJARFileExporter
The RunnableJarExportwizardallowsyoutocreatearunnableJARfile.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 269/322
12/10/2015 Javadevelopmentuserguide
RunnableJARfilespecification
RunnableJARSpecificationOptions:
Option Description
Launch Selecta'JavaApplication'launchconfigurationtousetocreatearunnableJAR.
configuration
Exportdestination EnteranexternalfilesystempathandnameforaJARfile(eitherneworexisting).EithertypeavalidfilepathinthefieldorclickBrowsetoselectafileviaa
dialog.
Libraryhandling Youcanselectanyofthefollowingoptions:
ExtractrequiredlibrariesintogeneratedJAR:toinflatethereferencedjarfilesandcopytheclassesintothegeneratedjar
PackagerequiredlibrariesintogeneratedJAR:tocopythereferencedjarfilesasisintothegeneratedjar
CopyrequiredlibrariesintoasubfoldernexttothegeneratedJAR
SaveasANT Ifyouselectthisoption,youcancreateanantscriptdescribingtheJARfileyouarecreating.Eithertypeand/orbrowsetoselectapathandnameforthisnew
script scriptfile.
CreatingRunnableJARfiles
Fileactions
5.10.11.OpenType
Thisdialogallowsyoutobrowsetheworkbenchforatypetoopeninaneditorortypehierarchy
Entertypenameprefixorpattern:Inthisfield,typethefirstfewcharactersofthetypeyouwanttoselect.
Thefollowingpatternkindsaresupported:
Wildcards:
"*"foranystringand"?"foranycharacter
terminating"<"or""(space)topreventtheautomaticprefixmatching,e.g."java.*Access<"tomatchjava.util.RandomAccessbutnot
java.security.AccessControlContext
Camelcase:
"TZ"fortypescontaining"T"and"Z"asuppercaselettersincamelcasenotation,e.g.java.util.TimeZone
"NuPoEx"or"NuPo"fortypescontaining"Nu","Po",(and"Ex")aspartsincamelcasenotation,e.g.java.lang.NullPointerException
terminating"<"or""(space)tofixthenumberofcamelcaseparts,e.g."HMap<"and"HaMap<"match"HashMap"and"HatMapper",butnot"HashMapEntry"nor
"Hashmap".
Bothpatternkindsalsosupportpackageprefixes,e.g."j.util.*Map<".
Matchingitems:ThislistdisplaysmatchesforthepatternyoutypeintheEntertypenameprefixorpatternfield.Recentlyopenedtypesshowupinahistorysectionatthe
topofthelist.
ThebehavioroftheOpenTypedialogcanbefurthercustomizedusingthedialogmenu:
OpenTypeOptions
Openinganeditoronatype
Workingsets
Typefilters
Navigateactions
5.10.12.CreateGettersandSetters
Thisdialogletsselectthegetterandsettermethodstocreate.
UseGenerateGettersandSettersfromtheSourcemenuorthecontextmenuonaselectedfieldortype,oratextselectioninatypetoopenthedialog.TheGenerateGettersand
Settersdialogshowsgettersandsettersforallfieldsoftheselectedtype.Themethodsaregroupedbythetype'sfields.
Thenamesofthegetterandsettermethodsarederivedfromthefieldname.Ifyouuseaprefixorsuffixforfields(e.g.fValue,_value,val_m),youcanspecifythesuffixesand
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 270/322
12/10/2015 Javadevelopmentuserguide
prefixesintheCodeStylepreferencepage(Windows>Preferences>Java>CodeStyle).
WhenpressingOK,allselectedgettersandsettersarecreated.
Option Description
Selectgettersandsettersto Atreecontaininggetterandsettermethodsthatcanbecreated.Gettersandsettersaregroupedbyfieldtheirassociatedfield.
create
SelectAll Selectallgetterandsettermethods
DeselectAll Deselectallgetterandsettermethods
SelectGetters Selectallgettermethods
Insertionpoint Defineswhereinthetypebodythenewmethodsareinserted
Defineshowtosortthenewmethods:
Sortby
ingetter/setterpairs
firstgetters,thensetters
Accessmodifiers Definestheaccessmodifiersofthenewmethods
Generatemethodcomments ControlswhetherJavadoccommentsareaddedtothecreatedmethods.ThecommenttemplatesaredefinedontheCodeTemplatespreference
page.
Sourceactions
5.10.13.GeneratetoString()dialog
TheGeneratetoString()dialogprovidesmeanstoincludespecificmemberfieldsandmethodsingeneratedtoString()method.
UseGeneratetoString()...fromtheSourcemenuorthecontextmenuonaselectedtypeoronatextselectioninatype.
ThememberstobeconsideredforinclusioninthetoString()outputare:
fields(nonstatic)
argumentlessmethods(nonstatic,nonvoid)
inheritedfieldsandmethods(fulfillingadequateconditions)
WhenpressingOK,thetoString()methodprintingoutallselectedmembersandeventuallyhelpermethodsarecreated.
Forconvenience,membersaredividedintouptofourgroups:Fields,Inheritedfields,MethodsandInheritedmethods. Onlyfieldswhicharenon
Selectfieldsandmethods Checkingoruncheckingagroupaffectsthestateofallitsmembers. transientandnotinherited.
toincludeinthetoString()
method
Up Movetheelementwithfocusupthelist.Amembercanbemovedonlywithinitsgroup.Groupscanalsobemoved. n/a
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 271/322
12/10/2015 Javadevelopmentuserguide
Codestyle Definesthemethodcodestyle,thatiswhatlibraries/mechanismsitusestocreateoutput.Formoreinformation,see Stringconcatenation
toString()generator:codestylestopic.
Sourceactions
toString()generator:formattemplates
toString()generator:codestyles
toString()generator:contentlisting
5.10.13.1.toString()Generator:FormatTemplates
Formattemplatesareusedbyasimplemechanismthatallowsyoutochangeformatofgeneratedmethod'soutputstring:beginning,ending,separator,andsoon.Theylooksimilar
toJDTcodetemplatesbuttheydon'taffectthegeneratedcodedirectly(CodeStylesareusedforthat).Here'salistofavailabletemplatevariables:
${object.className} insertstheclassnameasasimpleString
${object.getClassName} insertsacalltothis.getClass.getName()
${object.superToString} insertsacalltosuper.toString()
${object.hashCode} insertsacalltothis.hashCode()
${object.identityHashCode} insertsacalltoSystem.identityHashCode(this)
${member.name} insertsthefirstmember'sname
${member.name()} insertsthefirstmember'snamefollowedbyparenthesisincaseofmethods
${member.value} insertsthefirstmember'svalue
insertstheremainingmembers.Foreachmember,thetemplatefragmentbetweenthefirstandthelast${member.*}variableisevaluatedand
${otherMembers} appendedtotheresult.Thecharactersbetweenthelast${member.*}and${otherMembers}definetheseparatorthatisinsertedbetween
members(${otherMembers}muststandafterthelast${member.*}variable).
Forthetemplatetoworkproperly,the${otherMembers}variablemustbeusedexactlyonceinatemplateandcannotbefollowedbyany${member.*}variable.${object.*}variables
canbeplacedanywhereinthetemplate,althoughifoneisplacedinamemberrelatedfragment(thatisbetweenthefirst${member.*}variableand${otherMembers}),itwillbe
repeatedforeverymember,whichisprobablynotasensiblesolution.
Thedescriptionabovemightseemcomplicated,butthetemplateformatitselfisveryeasytouse.Itshouldallbecomeclearafterseeingsomeworkingexamples.
Templateexamples
1. Thedefaulttemplateisagoodexample:
${class.name}[${member.name()}=${member.value},${otherMembers}]
Theoutputstringforthistemplatelookslikethis:
FooClass[aFloat=1.0,aString=hello,anInt=10,anObject=null,aCharMethod()=a]
2. Multiplelineoutputisalsoavailable:
${object.getClassName}{
${member.name}:${member.value}
${otherMembers}
}
Exampleresult:
FooClass{
aFloat:1.0
aString:hello
anInt:10
anObject:null
aCharMethod:a
}
3. Ifyouencloseamemberinbraces,don'tforgettodothesamewith${otherMembers}variable:
{${member.name}=${member.value}},
{${otherMembers}}
Here'stheeffect:
{aFloat=1.0},
{aString=hello},
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 272/322
12/10/2015
{anInt=10},
Javadevelopmentuserguide
{anObject=null},
{aCharMethod=a}
4. ${object.*}variablescanbeusedatthebeginningandattheendofthetemplate:
${object.getClassName}(hashcode:${object.hashCode})
members:${member.name}=${member.value}${otherMembers}
[super:${object.superToString}]
Thistemplatewouldresultinanoutputsimilartothis:
FooClass(hashCode:232198409832)
members:aFloat=1.0aString=helloanInt=10anObject=nullaCharMethod=a
[super:SuperFooClass[aField=null]]
GeneratetoString()dialog
toString()Generator:CodeStyles
toString()Generator:ContentListing
5.10.13.2.toString()Generator:CodeStyles
Codestyledetermineshowthegeneratedmethodworksandwhatclassesituses.Thereareseveralcodestylesavailabletochosefromthecomboboxingenerator'sdialog:
Stringconcatenation
Thisstyleusessimplesumexpressionssoit'sveryefficient(compilerusesStringBuilder/StringBuffertooptimizethecode)andrelativelyeasytoreadandmodify.Here'san
exampleoutcomeinthesimplestcase:
return"FooClass[aFloat="+aFloat+",aString="+aString+",anInt="+anInt
+",anObject="+anObject+"]"
With"Skipnullvalues"optionturnedon,thecodebecomesalittlehardertoread:
return"FooClass[aFloat="+aFloat+","
+(aString!=null?"aString="+aString+",":"")
+"anInt="+anInt+","
+(anObject!=null?"anObject="+anObject:"")+"]"
StringBuilder/StringBuffer
ThisstyleusesStringBuilderiftheprojectiscompatiblewithJDK1.5orlaterandStringBufferotherwise.StringBuilderisfaster(becauseoflackofsynchronization),butonly
availablesinceJDK1.5.
StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=")
builder.append(aFloat)
builder.append(",aString=")
builder.append(aString)
builder.append(",anInt=")
builder.append(anInt)
builder.append(",anObject=")
builder.append(anObject)
builder.append("]")
returnbuilder.toString()
The"Skipnullvalues"optiondoesn'tobfuscatethecodeasmuchaspreviously:
StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=")
builder.append(aFloat)
builder.append(",")
if(aString!=null){
builder.append("aString=")
builder.append(aString)
builder.append(",")
}
builder.append("anInt=")
builder.append(anInt)
builder.append(",")
if(anObject!=null){
builder.append("anObject=")
builder.append(anObject)
}
builder.append("]")
returnbuilder.toString()
StringBuilder/StringBufferwithchainedcalls
Styleverysimilartothepreviousoneonlythatappendmethodsarecalledinchain.Thismakesthecodeshorterandprobablyeasiertoread.
StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=").append(aFloat).append(",aString=").append(aString)
.append(",anInt=").append(anInt).append(",anObject=").append(anObject).append("]")
returnbuilder.toString()
With"Skipnullvalues"switchedon,thechainmustbebroken:
StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=").append(aFloat).append(",")
if(aString!=null){
builder.append("aString=").append(aString).append(",")
}
builder.append("anInt=").append(anInt).append(",")
if(anObject!=null){
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 273/322
12/10/2015 Javadevelopmentuserguide
builder.append("anObject=").append(anObject)
}
builder.append("]")
returnbuilder.toString()
String.format()/MessageFormat
Thisstyleisverypleasantforrelativelyshortlistofelements,butwithlongeronesitbecomeshardtoseewhichfieldsareassociatedwithwhichvariables.Unfortunately,the
"Skipnullvalues"optioncannotbeusedwiththisstyle.
returnString.format("FooClass[aFloat=%s,aString=%s,anInt=%s,anObject=%s]",
aFloat,aString,anInt,anObject)
Becausethere'snoString.format()inJDK1.4andearlier,MessageFormat.format()isusedinstead:
returnMessageFormat.format("FooClass[aFloat={0},aString={1},anInt={2},anObject={3}]",
newObject[]{newFloat(aFloat),aString,newInteger(anInt),anObject})
CustomtoString()builder
Thisstyleusesanexternalclasstobuildaresultstring.Itcanuseclassesthatfulfillthefollowingconditions:
ProvideapublicconstructortakingasingleObjectasparameteritwillbepassedanobjectforwhichthetoString()methodiscalled
Providemethodsforappendingmemberinformationthesearemethodswithspecifiedname,thattakeanObjectand(optionally)aString(inanyorder)
ProvideamethodforretrievingresultthatisamethodtakingnoargumentsandreturningaString
Custombuilderrequiressomeadditionalconfigurationtoworkproperly.Allnecessaryoptionscanbeenteredinadialogboxshowingupafterclicking'Configure...'button.
Theseoptionsinclude:
Builderclassafullyqualifiednameofaclasstouse.Itcanbetypedinmanuallyorselectedfromaclasssearchdialogbox(inthiscaseit'sautomaticallycheckedif
selectedclassmeetstherequirements).Itcanbeaclassdeclaredeitherdirectlyincurrentprojectorinoneofincludedlibrariesitjusthastobeaccessibleonthebuild
path.Forexample,ToStringBuilderfromtheApacheCommonsLanglibraryorToStringCreatorfromtheSpringFrameworkworkverywellwiththismechanism.
Builderlabelanyvalidjavaidentifier.Itwillbeusedtoreferencethebuilderobject.
Appendmethodthenameofmethodstouseforappendingitems.Iftheclassprovidesmanymethodswiththisname,methodstakingtwoarguments(oneofthem
mustbeString)arepreferredoverthosetakingasingleargument(additionally,theStringargumentshallpreferablybethefirstone).Ifthereareversionsofthemethod
thattakespecificargumenttypes,theyarealsousedwhenpossible.
Resultmethodthenameofamethodtouseforretrievingfinalresult.
Chaininvocationsdetermineswhethercallstotheappendmethodsshouldformchains.Thisoptiontakeseffectonlyformethodsthathaveproperreturntype(thatis,
thebuilderclass,orasubclass).
Forexample,supposeyourbuilderclasslookslikethis:
packageorg.foo.ToStringBuilder2
publicclassToStringBuilder2{
publicToStringBuilder2(Objecto){...}
publicToStringBuilder2appendItem(Strings,Objecto){...}
publicToStringBuilder2appendItem(Strings,floatf){...}
publicStringgetString(){...}
}
Ofcourseinthiscasebuilderclassshouldbesetto"org.foo.ToStringBuilder2",builderlabelcanbeforexample"builder",appendmethodis"appendItem"and
resultmethodis"getString".Withchaininvocationsselected,generatedmethodwilllooklikethis:
ToStringBuilder2builder=newToStringBuilder2(this)
builder.append("aFloat",aFloat).append("aString",aString).append("anInt",newInteger(anInt))
.append("anObject",anObject)
returnbuilder.getString()
NotethataprimitivevariableanIntwaspassedtothebuilderusingwrappertype.ThisisdoneforprojectsusingJDK1.4andearlier(forlaterJDKsthecompilerdoesit
automatically).IncaseofaFloattherewasaspecificmethodinbuilderclasssonowrappingwasrequired.
GeneratetoString()dialog
toString()Generator:FormatTemplates
toString()Generator:ContentListing
5.10.13.3.toString()Generator:ContentListing
ThistopicdiscusseshowtoString()generatorlistscontentsofarraysandhowitlimitsnumberofitemslistedinCollectionsandMaps.Usedmethoddependsnotonlyonthe
membertype,butalsoonselectedJDKcompatibilityoftheproject.
ListingcontentsofArrays
Withoutlimitingnumberofelements
ForJDK1.5andlater,generatedmethodusesArrays.toString().AsthismethodisnotavailableinJDK1.4,Arrays.asList()isusedinsteadinthiscase,butonlyfornon
primitivearrays.Primitivearraysarehandledwithahelpermethod,showedbelow.
Limitingnumberofelements
Ifthearrayencloseanonprimitivetype,thesamesolutionisusedforallversionsofJDK:Arrays.asList()withList.subList().Forexample,foramembernamed
anArray,generatedcodelookslikethis:Arrays.asList(anArray).subList(0,Math.min(anArray.length,maxLen))
Incaseofprimitivearrays,Arrays.asList()cannotbeusedsoinJDK1.5orlowerahelpermethodisusedinstead.InJDK1.6there'sanothersolution:
Arrays.toString(Arrays.copyOf(anArray,Math.min(anArray.length,maxLen)).Althoughcopyinganarrayisnotanoptimalsolution,thecopiedpartisusuallyrather
smallandefficiencyisnotaffected.Agoodthingisthatahelpermethodcanbeavoided.
Helpermethod
Ahelpermethodreturnsastringlistingitemsofagivenarray,intheformof[1,2,3].Themethoditeratesoverthearrayandusesinstanceoftodetermineitsenclosing
type.Tomakethecodeshorter,itchecksonlyfortypesthatcanactuallybepassedtoit.
privateStringarrayToString(Objectarray,intlen,intmaxLen){
StringBufferstringBuffer=newStringBuffer()
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 274/322
12/10/2015 Javadevelopmentuserguide
len=Math.min(len,maxLen)
stringBuffer.append("[")
for(inti=0i<leni++){
if(i>0)
stringBuffer.append(",")
if(arrayinstanceoffloat[])
stringBuffer.append(((float[])array)[i])
if(arrayinstanceofint[])
stringBuffer.append(((int[])array)[i])
if(arrayinstanceofObject[])
stringBuffer.append(((Object[])array)[i])
}
stringBuffer.append("]")
returnstringBuffer.toString()
}
NOTES:
Thismethodisoverwritteneverytimethegeneratorruns.
Ifthenumberofitemsisnotlimited,themethoddoesn'ttakethemaxLenargumentanddoesn'tuseMath.min()
StringBufferorStringBuilderisuseddependingonselectedJDKcompatibility
ListinglimitedcontentsofLists
ThesamesolutionisusedforallJDKversions:aList.subList(0,Math.min(aList.size(),maxLen))
ListinglimitedcontentsofCollections(helpermethod)
ACollectioncannotbeturnedintoaListwithoutcopyingitscontents(assumingitisn'taListalready),soahelpermethodisusedtoiterateoverfirstmaxLenelementsandbuild
astringoutofthem:
privateStringtoString(Collectioncollection,intmaxLen){
StringBufferstringBuffer=newStringBuffer()
stringBuffer.append("[")
inti=0
for(Iteratoriterator=collection.iterator()iterator.hasNext()&&i<maxLeni++){
if(i>0)
stringBuffer.append(",")
stringBuffer.append(iterator.next())
}
stringBuffer.append("]")
returnstringBuffer.toString()
}
NOTES:
Thismethodisnotoverwritteneverytimethegeneratorruns,soitcanbeeasilycustomizedbyhand.
StringBuilderorStringBufferisuseddependingonselectedJDKcompatibility
ListinglimitedcontentsofMaps
IncaseofMaps,thesamehelpermethodisusedasforCollectionsonlythatmap.entrySet()ispassedtoit.
Summary
Thistablesumsupwhatmethodsareusedindifferentconditions:
helpermethod
jdk1.4/1.5, helpermethod
toString(collection, helpermethodarrayToString(array,
limit member.subList() toSting(collection, Arrays.asList(array).subList()
maxLen)with len,maxLen)
elements maxLen)
map.entrySet()
jdk1.6, helpermethod
helpermethod Arrays.toString(Arrays.copyOf(member,
limit member.subList() toString(Collection)with Arrays.asList(array).subList()
toString(Collection) ...))
elements map.entrySet()
Additionalnotes
Ifahelpermethodmustbegeneratedforatleastonemember,itisalsousedforothermemberswhenpossible.Forexample,aListisusuallyhandledwithsubList()
method,butifthere'sanothermemberofCollection(notList)typeandtoString(collection)isgenerated,Listsarealsopassedtoit.Thiswaythecodeisshorterandmore
consistent.
Wherenecessary,thecoderesponsibleforlistingcontentsissurroundedwithnullcheckingcode,forexample:array!=null?Arrays.asList(array):null
Ifmaximumnumberoflisteditemsissetto0,thegeneratorusessimplestringliteral("[]")insteadofmethodsdescribedabove.
GeneratetoString()dialog
toString()Generator:FormatTemplates
toString()Generator:CodeStyles
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 275/322
12/10/2015 Javadevelopmentuserguide
5.10.14.OverrideMethods
Thisdialogletsyoudefinemethodstooverride.
UseOverride/ImplementMethodsfromtheSourcemenuorthecontextmenuonaselectedtypeoronatextselectioninatype.
Thedialogpresentsallmethodsthatcanbeoverriddenfromsupertypesorimplementedfrominterfaces.Abstractmethodsorunimplementedmethodsareselectedbydefault.
Thetreeviewgroupsmethodsbythetypedeclaringthemethod.Ifmorethanonetypeinthehierarchydeclarethesamemethod,themethodisonlyshownonce,groupedtothefirst
typeinthelistofsupertypesthatimplementsordefinesthismethod.
Theflatviewshowsonlymethods,sortedalphabetically.
WhenpressingOK,methodstubsforallselectedmethodsarecreated.
Selectmethodstooverrideorimplement Abstractmethodsfromsuperclassesandunimplemented
Selectmethodsto methodsfrominterfacesareselected
overrideorimplement
Sourceactions
5.11.FrequentlyAskedQuestionsonJDT
CanIuseaJavacompilerotherthanthebuiltinone(javacforexample)withtheworkbench?
No.TheJDTprovidesanumberofsophisticatedfeaturesincludingfullyautomaticincrementalcompilation,codesnippetevaluation,codeassist,typehierarchies,andhotcode
replace.ThesefeaturesrequirespecialsupportfoundintheworkbenchJavacompiler(anintegralpartoftheJDT'sincrementalprojectbuilder),butnotavailableinstandardJava
compilers.
WheredoJavapackagescomefrom?
Aprojectcontainsonlyfilesandfolders.ThenotionofaJavapackageisintroducedbyaJavaproject'sclasspath(attheUI,thePackageExplorerpresentsthepackagesas
definedbytheclasspath).Tip:Ifthepackagestructureisnotwhatyouexpect,checkoutyourclasspath.TheJavasearchinfrastructureonlyfindsdeclarationsforandreferences
fromJavaelementsontheclasspath.
WhendoIuseaninternalversusanexternalJARlibraryfile?
Aninternalresourceresidesinsomeprojectintheworkbenchandisthereforemanagedbytheworkbenchlikeotherresources,theseresourcescanbeversionmanagedbythe
workbench.Anexternalresourceisnotpartoftheworkbenchandcanbeusedonlybyreference.Forexample,aJREisoftenexternalandverylarge,andthereisnoneedto
associateitwithaVCMsystem.
WhenshouldIusesourcefolderswithinaJavaproject?
EachJavaprojectlocatesitsJavasourcefilesviaoneormoresourcetypeentriesontheproject'sclasspath.Usesourcefolderstoorganizethepackagesofalargeprojectinto
usefulgrouping,ortokeepsourcecodeseparatefromotherfilesinthesameproject.Also,usesourcefoldersifyouhavefiles(documentationforexample)whichneednotbeonthe
buildpath.
Whataresourceattachments,HowdoIdefineone?
LibrariesarestoredasJARfilescontainingbinaryclassfiles(andperhapsotherresources).Thesebinaryclassfilesprovidesignatureinformationforpackages,classes,methods,
andfields.Thisinformationissufficienttocompileorrunagainst,butcontainsfarlessinformationthattheoriginalsourcecode.Inordertomakeiteasiertobrowseanddebugbinary
libraries,thereisamechanismforassociatingacorrespondingsourceJAR(orZIP)filewithabinaryJARfile.
Whyareallmyresourcesduplicatedintheoutputfolder(bin,forexample)?
IfyourJavaprojectisusingsourcefolders,theninthecourseofcompilingthesourcefilesintheproject,theJavacompilercopiesnonJavaresourcestotheoutputfolderaswellso
thattheywillbeavailableontheclasspathoftherunningprogram.ToavoidcertainresourcestobecopiedtotheoutputlocationyoucansetaresourcefilterintheJavacompiler
preferences:Window>Preferences>Java>Compiler>Building
HowdoIpreventhavingmydocumentationfilesfrombeingcopiedtotheproject'soutputfolder?
Usesourcefoldersandputanyresourcesthatyoudonotwanttobecopiedtotheoutputfolderintoaseparatefolderthatisnotincludedontheclasspath.Youcanalsoseta
resourcefilterintheJavacompilerpreferences:Window>Preferences>Java>Compiler>Buildingtoforexample*.doc.
HowdoIcreateadefaultpackage?
Youdon'thaveto.Filesintherootfolderofasourcefolderorprojectareconsideredtobeinthedefaultpackage.Ineffect,everysourcefolderhasthecapabilityofhavinga
fragmentofthedefaultpackage.
Whatisrefactoring?
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 276/322
12/10/2015 Javadevelopmentuserguide
Refactoringmeansbehaviorpreservingprogramtransformations.TheJDTsupportsanumberoftransformationsdescribedinMartinFowler'sbookRefactoring:ImprovingtheDesign
ofExistingCode,AddisonWisely1999.
WhendoIuseOpenDeclaration(F3)?
TofindouttheJavaelementthatcorrespondstotheselectedsourcerangewiththehelpofthecompiler.
IstheJavaprograminformation(typehierarchy,declarations,references,forexample)producedbytheJavabuilder?Isitstillupdatedwhenautobuild
isoff?
TheJavaprograminformationisindependentfromtheJavabuilder.ItisautomaticallyupdatedwhenperformingresourcechangesorJavaoperations.Inparticular,allthe
functionalityofferedbytheJavatooling(forexample,typehierarchies,codeassisting,search)willcontinuetoperformaccuratelywhenautobuildisoffforexample,whendoing
heavyrefactoringwhichrequiretoturnoffthebuilders,youcanstillusecodeassist,whichwillreflectthelatestchanges(notyetbuild).Otherthanthelaunching(thatis,runningand
debugging)ofprograms,theonlyfunctionalitywhichrequirestheJavabuilderistheevaluationofcodesnippets.
Afterreopeningaworkbench,thefirstbuildthathappensaftereditingaJavasourcefileseemstotakealongtime.Whyisthat?
TheJavaincrementalprojectbuildersavesitsinternalstatetoafilewhentheworkbenchisclosed.Onthefirstbuildaftertheprojectisreopened,theJavaincrementalproject
builderwillrestoreitsinternalstate.Whenthisfileislarge,theuserexperiencesanunusuallylongbuilddelay.
Ican'tseeatypehierarchyformyclass.WhatcanIdo?
Checkthatyouhaveyourbuildclasspathsetupproperly.SettinguptheproperbuildclasspathisanimportanttaskwhendoingJavadevelopment.Withoutthecorrectbuildpath,
youwillnotbeabletocompileyourcode.Inaddition,youwillnotbeabletosearchorlookatthetypehierarchiesforJavaelements.
HowdoIturnoff"autocompile"anddoitmanuallywhenIwant?
CleartheBuildautomaticallycheckboxonthe General>Workspacepreferencepage.Whenyouwanttobuild,pressCtrl+B,orselectProject>BuildAllfromthemenu
bar.
Hint:whenyouturn"autocompile"offandbuildmanually,youmayalsowanttoselecttheSaveautomaticallybeforebuildcheckboxonthe General>Workspacepreference
page.
WhenIselectamethodorafieldintheOutlineview,onlythesourceforthatelementisshownintheeditor.WhatdoIdotoseethesourceofthewhole
file?
ThereisatoolbarbuttonShowSourceofSelectedElementOnlyallyouhavetodoisunpressit.
CanInestsourcefolders?
Yes,youcanuseexclusionfilterstocreatenestedsourcefolders.
CanIhaveseparateoutputfoldersforeachsourcefolder?
Yes,selecttheAllowoutputfoldersforsourcefolderscheckboxintheJavaBuildPath>SourcepropertypageofyourJavaproject.
CanIhaveanoutputorsourcefolderthatislocatedoutsideoftheworkspace?
Yes,youcancreatealinkedfolderthatpointstothedesiredlocationandusethatfolderasthesourceoroutputfolderinyourJavaproject.
Javadevelopmenttools(JDT)
Javabuildpathpage
JDTglossary
5.12.JDTGlossary
CLASSfile
AcompiledJavasourcefile.
compilationunit
AJavasourcefile.
field
Afieldinsideatype.
importcontainer
Representsacollectionofimportdeclarations.ThesecanbeseenintheOutlineview.
importdeclaration
Asinglepackageimportdeclaration.
initializer
Astaticorinstanceinitializerinsideatype.
JARfile
JAR(Javaarchive)filesarecontainersforcompiledJavasourcefiles.Theycanbeassociatedwithanarchive(suchas,ZIP,JAR)asasourceattachment.ThechildrenofJAR
filesarepackages.JARfilescanbeeithercompressedoruncompressed.
JAVAelements
JavaelementsareJavaprojects,packages,compilationunits,classfiles,types,methodsandfields.
JAVAfile
Aneditablefilethatiscompiledintoabytecode(CLASS)file.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 277/322
12/10/2015
Javaprojects
Javadevelopmentuserguide
ProjectswhichcontaincompilableJavasourcecodeandarethecontainersforsourcefoldersorpackages.
JDT
Javadevelopmenttools.Workbenchcomponentsthatallowyoutowrite,edit,execute,anddebugJavacode.
JRE
Javaruntimeenvironment(forexample,J9,JDK,andsoon).
method
Amethodorconstructorinsideatype.
packagedeclaration
Thedeclarationofapackageinsideacompilationunit.
packages
AgroupoftypesthatcontainJavacompilationunitsandCLASSfiles.
refactoring
Acomprehensivecodeeditingfeaturethathelpsyouimprove,stabilize,andmaintainyourJavacode.Itallowsyoutomakeasystemwidecodingchangewithoutaffectingthe
semanticbehaviorofthesystem.
type
AtypeinsideacompilationunitorCLASSfile.
sourcefolder
AfolderthatcontainsJavapackages.
VCM
Versioncontrolmanagement.Thistermreferstothevariousrepositoryandversioningfeaturesintheworkbench.
VM
Virtualmachine.
Javadevelopmenttools(JDT)
FrequentlyaskedquestionsonJDT
5.13.JDTIcons
Objects
compilationunit(*.javafile)
Javafilewhichisnotonabuildpath
classfile
genericfile(unknowncontenttype)
unknownobject
Javascrapbookpage(*.jpagefile)
Javascrapbookpage(evaluationin
progress)
JARdescriptionfile
JUnittestresultfile
Javaworkingset
Javamodel
librarycontainer
JARfilewithattachedsource
JARfilewithoutattachedsource
classfolderwithattachedsource
classfolderwithoutattachedsource
sourcefolder
package
emptypackage
logicalpackage
emptylogicalpackage
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 278/322
12/10/2015 Javadevelopmentuserguide
packageonlycontainingnonJavaresources
packagedeclaration
importcontainer
import
class(public)
interface(public)
enumtype(public)
annotationtype(public)
packagevisibleclass
privateclass
protectedclass
defaultfield(packagevisible)
privatefield
protectedfield
publicfield
defaultmethod(packagevisible)
privatemethod
protectedmethod
publicmethod
Objectadornments
marksprojectasJavaproject
decoratesfilesandfoldersiftheyareonthe
buildpathoftheirenclosingJavaproject
decoratesJavaprojectsandworkingsets
thatcontainbuildpatherrors
thisJavaelementcausesanerror
thisJavaelementcausesawarning
thisJavaelementisdeprecated
constructor
abstractmember
finalmember
staticmember
synchronizedmember
nativemethod
transientfield
volatilefield
typewith
publicstaticvoidmain(String[]args)
implementsmethodfrominterface
overridesmethodfromsuperclass
typewithfocusinTypeHierarchyorQuick
Outline/Hierarchy
maximalexpansionlevelinCallHierarchy
recursivecallinCallHierarchy
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 279/322
12/10/2015 Javadevelopmentuserguide
compilationunitcontaininganabstractclass
asprimarytype
compilationunitcontaininganinterfaceas
primarytype
compilationunitcontaininganenumas
primarytype
compilationunitcontaininganannotationas
primarytype
Buildpath
classpathvariable
JARwithattachedsource
JARwithoutattachedsource
systemlibrary
buildpathordering
inclusionfilter
exclusionfilter
accessrules
Javadoclocation
sourceattachment
nativelibrarylocation
outputfolder
Codeassist
HTMLtag
Javadoctag
localvariable
template
SWTtemplate
Compare
field
method
Debugger
debuglaunch
runlaunch
terminatedrunlaunch
process
terminatedprocess
debugtarget
suspendeddebugtarget
terminateddebugtarget
thread
suspendedthread
stackframe
runningstackframe
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 280/322
12/10/2015
adornmentthatmarksastackframethat
Javadevelopmentuserguide
maybeoutofsynchwiththetargetVMasa
resultofanunsuccessfulhotcodereplace
adornmentthatmarksastackframethatis
outofsynchwiththetargetVMasaresult
ofanunsuccessfulhotcodereplace
inspectedobjectorprimitivevalue
watchexpression
localvariable
monitor
amonitorincontention
athreadincontentionforamonitor
amonitorthatisownedbyathread
athreadthatownsamonitor
currentinstructionpointer(topofstack)
currentinstructionpointer
enabledlinebreakpoint
disabledlinebreakpoint
adornmentthatmarksabreakpointas
skipped
adornmentthatmarksalinebreakpointas
installed
adornmentthatmarksabreakpointas
conditional
adornmentthatmarksanentrymethod
breakpoint
adornmentthatmarksanexitmethod
breakpoint
fieldaccesswatchpoint
fieldmodificationwatchpoint
fieldaccessandmodificationwatchpoint
adornmentthatmarksawatchpointas
installed
exceptionbreakpoint
runtimeexceptionbreakpoint
disabledexceptionbreakpoint
adornmentthatmarksanexception
breakpointascaught
adornmentthatmarksanexception
breakpointasuncaught
adornmentthatmarksanexception
breakpointasscoped
adornmentthatmarksanexception
breakpointasinstalled
Editor
implements
overrides
quickassistavailable
searchmatch
JUnit
test
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 281/322
12/10/2015
currentlyrunningtest
Javadevelopmentuserguide
successfultest
failingtest
testthrowinganexception
ignoredtest
testwithanassumptionfailure
testsuite
currentlyrunningtestsuite
successfullycompletedtestsuite
testsuitewithfailingtest
testsuitewithexceptionthrowingtest
caughtexception
stackframeelement
NLStools
skippedNLSkey
translatedNLSkey
untranslatedNLSkey
Quickfix
quickfixableerror
quickfixablewarning
add
change
changecast
fixmultipleproblems
movetoanotherpackage
remove
removeimport
rename
renameinfile
surroundwithtry/catch
Refactoring
generalchange
compositechange
textchange
filechange
Stoperror
Error
Warning
Information
Changefilter
Search
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 282/322
12/10/2015 Javadevelopmentuserguide
JavaSearch
searchfordeclarations
searchforreferences
SearchOccurrencesinFile
ageneralmatch
readaccesstolocalorfield
writeaccesstolocalorfield
TypeHierarchyview
typeoutsideofselectedpackage
interfaceoutsideofselectedpackage
5.16.ListofJDTkeybindings
ThelistofavailablekeybindingsinEclipsedependsonmanyfactors,includingwhatvieworeditorisselected,whetheradialogisopen,whatpluginsareinstalled,andwhat
operatingandwindowingsystemisbeingused.Atanytime,youcanobtainalistofavailablekeybindingsusingKeyAssist( Help>KeyAssist...orCtrl+Shift+L).Thefollowing
tableslistsomepopularkeybindingsavailableintheJavadevelopmenttools.
Javaeditoractions
AddBlockComment Ctrl+Shift+/
AddImport Ctrl+Shift+M
ContentAssist Ctrl+Space
ContentAssist(SimplifiedChinese) Alt+/
ExpandSelectiontoEnclosingElement Alt+Shift+UpArrow
ExpandSelection:RestoreLastSelection Alt+Shift+DownArrow
ExpandSelectiontoNextElement Alt+Shift+RightArrow
ExpandSelectiontoPreviousElement Alt+Shift+LeftArrow
Format Ctrl+Shift+F
Next Ctrl+.(Period)
OpenExternalJavadoc Shift+F2
OpenonSelection F3
OpenType Ctrl+Shift+T
OpenTypeHierarchy F4
OpenTypeinHierarchy Ctrl+Shift+H
OrganizeImports Ctrl+Shift+O
ParameterHints Ctrl+Shift+Space
ParameterHints(SimplifiedChinese) Alt+?
Previous Ctrl+,(Comma)
QuickAssist Ctrl+1
QuickFix Ctrl+1
Redo Ctrl+Y
RemoveBlockComment Ctrl+Shift+\
SearchforDeclarationsinWorkspace Ctrl+G
SearchforReferencesinWorkspace Ctrl+Shift+G
ShiftRight Tab
ShiftLeft Shift+Tab
ShowTooltipDescription F2
ToggleComment Ctrl+/
Undo Ctrl+Z
Debugactions
DebugLastLaunched F11
Display Ctrl+Shift+D
Inspect Ctrl+Shift+I
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 283/322
12/10/2015 Javadevelopmentuserguide
Resume F8
RunLastLaunched Ctrl+F11
RunSnippet Ctrl+U
RuntoLine Ctrl+R
RuntoReturn F7
StepInto F5
StepintoSelection Ctrl+F5
StepOver F6
ToggleBreakpoint Ctrl+Shift+B
Navigatingtheuserinterfaceusingthekeyboard
Keysandaccessibilityfortheworkbench
Listofkeybindings
6.TipsandTricks(JDT)
Thefollowingtipsandtricksgivesomehelpfulideasforincreasingyourproductivity.SeealsoPlatformTipsandTricksforgeneralEclipsetipsandWhat'sNew(JDT)forfeaturesin
thisrelease.
Editing|Refactoring|Searching|Navigation|Views|Miscellaneous|Debugging
Editingsource
Contentassist Contentassistprovidesyouwithalistofsuggestedcompletionsforpartiallyentered
strings.IntheJavaeditorpressCtrl+SpaceoruseEdit>ContentAssist.
Contentassistin ContentassistisalsoavailableinJavadoccomments.
Javadoc
comments
Contentassistfor Togetcontentassistproposalsforstaticmembersconfigureyourlistoffavoritestatic
staticimports membersonthe Java>Editor>ContentAssist>Favoritespreferencepage.
Forexample,ifyouhaveaddedjava.util.Arrays.*tothislist,thenallstaticmethodsof
thistypematchingthecompletionprefixwillbeaddedtotheproposalslist:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 284/322
12/10/2015 Javadevelopmentuserguide
Suppresstypesin Toexcludecertaintypesfromappearingincontentassist,usethetypefilterfeature
contentassist configuredonthe Java>Appearance>TypeFilterspreferencepage.Typesmatching
oneofthesefilterpatternswillnotappearintheOpenTypedialogandwillnotbeavailable
tocontentassist,quickfixandorganizeimports.Thesefilterpatternsdonotaffectthe
PackageExplorerandTypeHierarchyviews.
Contentassistfor Youcanusecontentassisttospeedupthecreationoffields,methodparametersandlocal
variable,method variables.Withthecursorpositionedafterthetypenameofthedeclaration,press
parameterand Ctrl+SpaceoruseEdit>ContentAssist.
fieldname
completions
Ifyouuseanameprefixorsuffixforfields,localvariablesormethodparameters,besure
tospecifythisinthe Java>CodeStylepreferencepage.
Contentassistfor Codeassistalsoworksonaccessestotypesthatarenotimportedyet.Dependingonthe
variablewith Java>Editor>ContentAssist>Addimportinsteadofqualifiednamepreference
unresolvedtype theeditorwilleitherautomaticallyaddimportsorfullyqualifythetypesforsuchproposals.
Pressinginthefollowingscenario:
resultsin:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 285/322
12/10/2015 Javadevelopmentuserguide
Contentassist Contentassistcanproposemembersavailableontypesusedininstanceofconditions.
afterinstanceof
condition
Eclipsewilladdtherequiredcastforyouwhenyouselectsuchaproposal.
Parameterhints Withthecursorinamethodargument,youcanseealistofparameterhints.IntheJava
EditorpressCtrl+Shift+SpaceorinvokeEdit>ContentAssist>ParameterHints.
Contentassiston Contentassistalsoprovideshelpwhencreatingananonymousclass.Withthecursor
anonymous positionedafter"new"andthebeginningofanabstractclassorinterfacenamepress
classes Ctrl+SpaceorinvokeEdit>ContentAssist>Default.
Thiswillcreatethebodyoftheanonymousinnerclassincludingallmethodsthatneedto
beimplemented.
Thisalsoworksifyouplacethecaretaftertheopeningparenthesesofaclassinstance
creation:
Togglebetween Whencontentassistisinvokedonanexistingidentifier,itcaneitherreplacetheidentifier
insertingand withthechosencompletionordoaninsert.Thedefaultbehavior(overwriteorinsert)is
replacingcontent definedinthe Java>Editor>ContentAssistpreferencepage.
assist Youcantemporarilytogglethebehaviorwhileinsidethecontentassistselectiondialogby
pressingandholdingtheCtrlkeywhileselectingthecompletion.
Incremental ContentassistcanalsoInsertcommonprefixesautomatically,similartoUnixshell
contentassist expansion.Toenablethatbehavior,selectthecheckboxonthe Java>Editor>
ContentAssistpreferencepage.
Camelcase Codecompletionsupportscamelcasepatterns.Forexample,completingonNPEor
supportincode NuPoiEwillproposeNullPointerException.Thissupportcanbedisabledusingthe
completion Showcamelcasematchespreferenceonthe Java>Editor>ContentAssist
preferencepage.
Use''keyto Youcanusethesemicolon()keytoselectanymethodinvocationproposalfromthe
insertmethod contentassistpopup.The' 'willbeappendedattheendofthemethodinvocation.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 286/322
12/10/2015
invocation
Javadevelopmentuserguide
Customizecontent Repeatedlyinvokingcontentassist(Ctrl+Space)cyclesthroughdifferentproposal
assistcategories categories.
Toconfigurewhichcategoriestoshowusethe Java>Editor>ContentAssist>
Advancedpreferencepage.
Youcanalsoassignseparatekeyshortcutstoyourfavoriteproposalcategories.
Creategettersand Tocreategetterandsettermethodsforafield,selectthefield'sdeclarationandinvoke
setters Source>GenerateGetterandSetter.
Ifyouuseanameprefixorsuffixbesuretospecifythisinthe Java>CodeStyle
preferencepage.
Creategettersand Aquickassist(Ctrl+1)isavailableonfieldstocreategettersandsetters.
settersquick
assist
Usecontentassist Anotherwaytocreategettersandsettersisusingcontentassist.Setthecursorinthetype
tocreategetter bodybetweenmembersandpressCtrl+Spacetogettheproposalsthatcreateagetteror
andsetters settermethodstub.
Deletegettersand Whenyoudeleteafieldfromwithinaview,EclipsecanproposedeletingitsGetterand
setterstogether Settermethods.Ifyouuseanameprefixorsuffixforfields,besuretospecifythisinthe
withafield Java>CodeStylepreferencepage.
Createdelegate Tocreateadelegatemethodforafieldselectthefield'sdeclarationandinvokeSource>
methods GenerateDelegateMethods.Thisaddstheselectedmethodstothetypethatcontainsa
forwardcalltodelegatedmethods.Thisisanexampleofadelegatemethod:
CreatehashCode() TocreatethemethodshashCode()andequals()invokeSource>GeneratehashCode()
andequals() andequals().
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 287/322
12/10/2015 Javadevelopmentuserguide
Usetemplatesto TemplatesareshowntogetherwiththeContentAssist(Ctrl+Space)proposals.
createamethod Thereareexistingtemplates,suchas'private_method','public_method',
'protected_method'andmore,butyoucanalsodefinenewtemplatesformethodstubs.
Afterapplyingatemplate,usetheTabkeytonavigateamongthevaluestoenter(return
type,nameandarguments).
Usetemplatesto OnprojectswhichhavetheSWTlibraryontheclasspath,youcancreateSWTwidgets
createSWT withContentAssist(Ctrl+Space)
widgets
Toadd,forexample,anSWTbutton,typeButtonandpressCtrl+Space,selecttheButton
SWTtemplate,andpressEnter.
Toseeallavailabletemplatesgotothe Java>Editor>Templatespreferencepageor
opentheTemplatesviewthroughWindow>ShowView>Other....
UseQuickFixto StartwiththemethodinvocationanduseQuickFix(Ctrl+1)tocreatethemethod.
createanew
method
UseQuickFixto Addanargumenttoamethodinvocationatacallsite.ThenuseQuickFix(Ctrl+1)toadd
changeamethod therequiredparameterinthemethoddeclaration.
signature
Usecontentassist Atthelocationwhereyouwanttoaddthenewconstructor,usecontentassistaftertyping
tocreatea thefirstlettersoftheconstructorname.
constructorstub
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 288/322
12/10/2015 Javadevelopmentuserguide
Createnewfields Doyouneedtocreatenewfieldstostoretheargumentspassedintheconstructor?Use
fromparameters QuickAssist(Ctrl+1)onaparametertocreatetheassignmentandthefielddeclaration
andletEclipseproposeanameaccordingtoyourCodeStylepreferences.
Usecontentassist InvokeContentAssist(Ctrl+Space)inthetypebodyatthelocationwherethemethod
tooverridea shouldbeadded.Contentassistwillofferallmethodsthatcanbeoverridden.Amethod
method bodyforthechosenmethodwillbecreated.
UseQuickFixto Toimplementanewinterface,addthe'implements'declarationfirsttothetype.Even
add withoutsavingorbuilding,theJavaeditorwillunderlinethetypetosignalthatmethodsare
unimplemented missingandwillshowtheQuickFixlightbulb.ClickonthelightbulborpressCtrl+1(Edit
methods >QuickFix)tochoosebetweenaddingtheunimplementedmethodsormakingyourclass
abstract.
UseCleanUpto Whenyouaddanewmethodtoaninterfaceoranabstractmethodtoanabstractclass,
add Eclipsecangeneratemethodstubsinallconcretesubclassesatonce.InvokeSource>
unimplemented CleanUp...onasetofJavaelements,useacustomprofile,andselectonthe
methods Configure...dialogtoAddunimplementedmethodsontheMissingCodetab.
Overrideamethod Tocreateamethodthatoverridesamethodfromabaseclass:
fromabaseclass SelectthetypewherethemethodsshouldbeaddedandinvokeSource>
Override/ImplementMethods.Thisopensadialogthatletsyouchoosewhichmethodsto
override.
Renameinfile Toquicklydoarenamethatdoesn'trequirefullanalysisofdependenciesinotherfiles,use
the'Renameinfile'QuickAssist.IntheJavaEditor,positionthecursorinanidentifierofa
variable,methodortypeandpressCtrl+1(Edit>QuickFix)
Theeditorisswitchedtothelinkededitmode(liketemplates)andchangingtheidentifier
simultaneouslychangesallotherreferencestothatvariable,methodortype.
YoucanalsousethedirectshortcutCtrl+2R.Usethe General>Keyspreference
pagetoconfigureshortcuts(inthe'Source'category).
UseQuickFixto Dealingwiththrownexceptionsiseasy.Unhandledexceptionsaredetectedwhiletyping
handleexceptions andmarkedwitharedlineintheeditor.
ClickonthelightbulborpressCtrl+1tosurroundthecallwithatrycatchblock.If
youwanttoincludemorestatementsinthetryblock,selectthestatementsanduse
Source>SurroundWith>Try/catchBlock.Youcanalsoselectindividual
statementsbyusingEdit>ExpandSelectionToandselectingEnclosing,Nextor
Previous.
Ifthecallisalreadysurroundedwithatryblock,QuickFixwillsuggestaddingthe
catchblocktotheexistingblock.
Ifyoudon'twanttohandletheexception,letQuickFixaddanewthrownexception
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 289/322
12/10/2015 totheenclosingmethoddeclaration Javadevelopmentuserguide
Atanytime,youcanconvertacatchblocktoathrownexception.UseCtrl+1(Edit>
QuickFix)onacatchblock.
Lesstypingfor Insteadoftypinganassignment,startwiththeexpressionthatwillbeassigned.
assignments
NowuseCtrl+1(Edit>QuickFix)andchoose'Assignstatementtonewlocalvariable'
andQuickAssistwillguessavariablenameforyou.
Lessworkwith Don'tspendtoomuchtimewithtypingcasts.Ignorethemfirstandusequickassisttoadd
castexpressions themafterfinishingthestatement.
Forexampleonassignments:
Orformethodarguments:
Orformethodcalltargets:
Assignacast Afteran'instanceof'check,itisverycommontocasttheexpressionandassignittoa
expression newlocalvariable.InvokeQuickAssist(Ctrl+1)onthe'instanceof'keywordoratthe
beginningoftheblockbodytosaveyourselfsometyping:
Surroundlines Tosurroundstatementswithanif/while/forstatementorablock,selectthelinesto
surroundandinvokeSource>SurroundWithorpressAlt+Shift+Z.
Theentriesinthemenuarederivedfromthenormaleditortemplates:Alltemplatesthat
containthevariable${line_selection}willshowupinthemenu.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 290/322
12/10/2015 Javadevelopmentuserguide
Templatescanbeconfiguredonthe Java>Editor>Templatespreferencepage.Edit
thecorrespondingtemplatestocustomizetheresultingcodeordefineyourownsurround
withtemplates.
Create'for'loops AsetofQuickAssists(Ctrl+1)cancreateforloopsthatiterateoveragivenexpression.
Forarrays:
Createanenhancedforloop
Createaforloopusinganindex
ForCollections:
Createanenhancedforloop
CreateaforloopusinganIterator
ForLists:
Createaforloopusinganindexandget(i)
Migrate Youcanconvertanonymousclasscreationstolambdaexpressions(andback)byinvoking
anonymousclass theQuickAssists(Ctrl+1):
creationsto
lambda Converttolambdaexpression
expressionsand Converttoanonymousclasscreation
back
Before:
AftertheQuickAssist(Ctrl+1),the6linesarecondensedinto1:
OrinvokeSource>CleanUp...,useacustomprofile,andontheConfigure...dialog
selectConvertfunctionalinterfaceinstancesandUselambdawherepossibleonthe
CodeStyletab.
Migrate Youcanconvertlambdaexpressionstomethodreferences(andback)byinvokingthe
lambda QuickAssists(Ctrl+1):
expressionsto
Converttomethodreference
methodreferences
andback
Converttolambdaexpression
MoreQuick CheckouttheQuickAssistpageforacompletelistofavailablecodetransformations.A
AssistsandFixes listofquickfixescanbefoundhere.
Shortcutsfor SomeofthepopularquickassistslikeRenameinfileandAssigntolocalvariablecan
QuickFixesand beinvokeddirectlywithCtrl+2RandCtrl+2L.Checkthe General>Keyspreference
Assists pageformorequickfixesandquickassiststhatsupportdirectinvocation.
Type"QuickAssist"or"QuickFix"inthefilterfield:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 291/322
12/10/2015 Javadevelopmentuserguide
Annotate YoucaninvokeAnnotatecommandeitherbyusingthecontextmenu,orbypressing
command Ctrl+1whenbrowsingattachedsourcecodeofalibraryusingtheclassfileeditorto
annotateanytypeinthesignatureofalibrarymethodorfield.Proposalswillbeofferedfor
markingtheselectedtypeas@[email protected],the
compilerwillimmediatelyleveragethenewannotationforitsnullanalysis.
Twoprerequisitesmustbemetforusingthiscommand:
Theprojectisconfiguredtouseannotationbasednullanalysis.
Anexistingworkspacefolderhasbeenspecifiedastheexternalannotationlocation
foragivenlibrary.
Contentassistcan Youcanhavecontentassistinsertargumentnamesautomaticallyonmethodcompletion.
insertargument Thisbehaviorcanbecustomizedonthe Java>Editor>ContentAssistpreference
names page(seetheFillmethodargumentsandshowguessedargumentscheckbox.)For
automatically example,whenyouselectthesecondentryhere,
contentassistwillautomaticallyinsertargumentnames:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 292/322
12/10/2015 Javadevelopmentuserguide
YoucanthenusetheTabkeytonavigatebetweentheinsertednames.
IfyouchooseInsertbestguessedarguments,thebestguesswillbefilledinbydefault.
Thealternativeproposalsarestillavailable.
resultsin:
Removetype Ifcontentassistaddedtypeargumentsforagenerictype,butyoudonotwantthem
argumentsafter becauseyouneedthe.classliteraloryouwanttoinvokeastaticmethod,ratherthan
contentassist deletingalltheargumentsmanually,youcanjustdeletethe' <'andthatwillremovethe
entiretextupto' >'.
Remove Toremoveasurroundingstatementorblock,positionthecursorattheopeningorclosing
surrounding bracketandpressCtrl+1(Edit>QuickFix).
statement
Youcanmakethedictionaryalsoavailabletothecontentassist.AQuickFixallowsyouto
addnewwordstotheuserdictionaryonthefly.
Structured TheStructuredSelectionactionscanbeusedtoenlargethecurrentselectiontothenext
selections enclosingelement:
HighlightsometextandpressAlt+Shift+ArrowUporselectEdit>ExpandSelectionTo
>EnclosingElementfromthemenubartheselectionwillbeexpandedtothesmallest
Javasyntaxelementthatcontainstheselection.Youcanthenfurtherexpandtheselection
byinvokingtheactionagain(orotheractionsfromtheExpandSelectionTomenu).
Thisisforexamplehelpfultoselecttheenclosingidentifierforrenames,ortoselect
adjacentstatementsforasubsequentExtractMethodrefactoring.
Findthematching TofindamatchingbracketselectanopeningorclosingbracketandpressCtrl+Shift+Por
bracket selectNavigate>GoTo>MatchingBracket.Youcanalsodoubleclicknexttoa
bracketthisselectsthetextbetweenthetwobrackets.
TheJavaeditoralsosupportshighlightingofenclosingbrackets.
Thiscanbeconfiguredonthe Java>Editorpreferencepage.
SmartJavadoc Type'/**'andpressEnter.ThisautomaticallyaddsaJavadoccommentstubcontaining
thestandard@param,@returnand@exceptiontags.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 293/322
12/10/2015 Javadevelopmentuserguide
Thetemplatesforthenewcommentcanbeconfiguredinthe Java>CodeStyle>
CodeTemplatespreferencepage.
Usethelocal Wheneveryoueditafile,itspreviouscontentsarekeptinthelocalhistory.Javatooling
historytorevert makesthelocalhistoryavailableforJavaelements,soyoucanrevertbacktoaprevious
backtoaprevious editionofasinglemethodinsteadofthefullfile.
editionofa
method Selectanelement(e.g.intheOutlineview)anduseReplaceWith>LocalHistoryto
revertbacktoapreviouseditionoftheelement.
Usethelocal Wheneveryoueditafile,itspreviouscontentsarekeptinthelocalhistory.Javatooling
historytorestore makesthelocalhistoryavailableforJavaelements,soyoucanrestoredeletedmethods
removedmethods selectively.
Selectacontainer(e.g.intheOutlineview)anduseRestorefromLocalHistoryto
restoreanyremovedmembers.
Since3.1,itispossibletouseprojectspecificCodetemplates,thatwillalsobesharedin
theteamifyourprojectisshared.OpenthePropertiesonaprojecttoenableproject
specificsettings.
Createcomments CommentscanbeaddedexplicitlywithSource>GenerateElementComment
inyourcode (Alt+Shift+J)orautomaticallybyvariouswizards,refactoringsorquickfixes.
Configurethecommenttemplatesonthe Java>CodeStyle>CodeTemplates
preferencepage.
Enableordisabletheautomaticgenerationofcommentseitherdirectlyonthewizard(e.g.
using'GenerateComment'checkboxonthenewJavatypewizards)orbythe
'Automaticallyaddnewcommentsfornewmethodsandtypes'checkboxofthe
Java>CodeStyle>CodeTemplatespreferencepage.
Allthesesettingscanalsobeconfiguredonaperprojectbasis.OpenthePropertiesona
projecttoenableprojectspecificsettings.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 294/322
12/10/2015
Sortmembers Javadevelopmentuserguide
YoucanSortMembersofaJavacompilationunitorasetofcompilationunitsaccording
toacategoryorderdefinedinthe Java>Appearance>MembersSortOrder
preferencepage.
You'llfindtheactionunderSource>SortMembers.
Wrapstrings YoucanhaveStringliteralswrappedwhenyoueditthem.Forexample,ifyouhavecode
likethis:
Stringmessage="Thisisaverylongmessage."
positionyourcaretaftertheword"very"andpressEnter.Thecodewillbeautomatically
changedto:
Stringmessage="Thisisavery"+
"longmessage."
Thisbehaviorcanbecustomizedinthe Java>Editor>Typingpreferencepage.
SmartTypingand TheJavaeditor'sSmartTypingfeatureseaseyourdailywork.Youcanconfigurethemon
howtocontrolit the Java>Editor>Typingpreferencepage.
WhenyouenableAutomaticallyinsertSemicolonsatcorrectposition,typinga
semicolonautomaticallypositionsthecursorattheendofthestatementbeforeinserting
thesemicolon.Thissavesyousomeadditionalcursornavigation.
Youcanundothisautomaticpositioningbypressingbackspacerightafterwards.
Fixyourcode AusefulfeatureisSource>CorrectIndentationorCtrl+I.
indentationwith Selectthecodewheretheindentsareincorrectandinvoketheaction.
onekeystroke
Ifnothingisselected,theactionindentsthecurrentline.
Fixyourcode Eclipsecancorrecttheindentationofyourcodewhenyousavetheeditor.Gotothe
indentationon Java>Editor>SaveActionspreferencepageandConfigure...Additionalactions,and
save selecttoCorrectindentationontheCodeOrganizingtab.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 295/322
12/10/2015 Javadevelopmentuserguide
Quickmenusfor Therefactoringandsourceactionscanbeaccessedviaaquickmenu.Selecttheelement
sourceand tobemanipulatedintheJavaeditororinaJavaviewandpressAlt+Shift+Sforthequick
refactoringactions sourcemenu,Alt+Shift+TforthequickrefactoringmenuandAlt+Shift+Zforthesurround
withmenu.
Findunusedcode TheJavacompilerdetectsunreachablecode,unusedvariables,parameters,importsand
unusedprivatetypes,methodsandfields.Changethesettingsforthedetectiononthe
Java>Compiler>Error/Warningspreferencepage.Thesesettingscanalsobe
specifiedperproject,use:Project>Properties>JavaCompiler>Error/Warnings.
Theseproblemsaredetectedasyoutype,andaquickfixisofferedtoremovethe
unneededcode.YoucanalsouseSource>CleanUp...toremoveunusedcode.
Findproblems Thecompilercanhelpyoufindproblemswithnullinyourcode.The Java>Compiler
withnull >Errors/Warningspreferencepagehasthreeoptionstodetectproblems:
Nullpointeraccess(in'Nullanalysis')
Whenthisoptionisenabled,thecompilerwillissueanerrororwarningwhenevera
variablethatisstaticallyknowntoholdanullvalueisusedtoaccessafieldor
method,asshownintheexamplebelow:
Potentialnullpointeraccess(in'Nullanalysis')
Whenthisoptionisenabled,thecompilerwillissueanerrororawarningwhenevera
variableisstaticallyknowntopotentiallyholdanullvalue,asshownintheexample
below:
Redundantnullcheck(in'Nullanalysis')
Whenenabled,thecompilerwillissueanerrororawarningwheneveravariablethat
isstaticallyknowntoholdanulloranonnullvalueistestedagainstnull,asshownin
theexamplesbelow:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 296/322
12/10/2015 Javadevelopmentuserguide
Findproblems TheSource>FindBrokenExternalizedStringsactionfindsundefined,unusedand
withexternalized duplicatekeysforyou:
strings
Changeproblem Whenaproblemhoverhasbeenenriched(bypressingF2ormovingthemouseintothe
severityin hover),anactiontochangetheseverityofthecurrentproblemisavailable.
problemhover
Clickonthebuttoninthetoolbartogotothe Java>Compiler>Errors/Warnings
preferencepage.
Javadoccomment TheEclipseJavacompilercanprocessJavadoccomments.Searchreportsreferencesin
handling doccomments,andrefactoringupdatesthesereferencesaswell.Thisfeatureiscontrolled
fromthe Java>Compiler>Javadocpreferencepage(orsetforanindividualproject
usingProject>Properties>JavaCompiler>Javadoc).
Whenturnedon,malformedJavadoccommentsaremarkedintheJavaeditorandcanbe
fixedusingEdit>QuickFix(Ctrl+1):
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 297/322
12/10/2015 Javadevelopmentuserguide
Suppress InJ2SE5.0andlater,youcansuppressalloptionalcompilewarningsusingthe
warnings SuppressWarningsannotation.
Inthisexample,addAll()ismarkedasanunusedmethod.QuickFix(Ctrl+1)isusedto
addaSuppressWarningsannotationsothatthewarningwillnotbeshownforthismethod.
CleanUps Source>CleanUp...helpsfixingmultipleproblemsatonceandhelpstoestablisha
consistentcodestyle.Forinstance,youcan:
convertallforloopstoenhancedforloopswherepossible.
markalloverridingmethodsinawholeprojectwithan@Overrideannotation.
organizeimports
formatyourcode
removeunnecessarycode
CleanUpsareorganizedinCleanUpprofiles.Aprofilecanbeattachedtotheworkspace
ortoindividualprojects.Projectsettingscanbesharedinateamthroughaversioncontrol
system.Itisalsopossibletoexportandimporteachprofile.
CleanUpscanbeexecutedassaveactionsonsave.Gotothe Java>Editor>Save
Actionspreferencepagetoconfigurewhichcleanupstoinvokeonsave.
Refactoring
Scriptingof MostoftherefactoringsofferedbyJDTcannotonlybeexecutedinteractively,butalso
refactorings byarefactoringscript.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 298/322
12/10/2015 Javadevelopmentuserguide
CreatearefactoringscriptfromtherefactoringhistoryusingRefactor>CreateScript....
ArefactoringscriptcanthenbeappliedlateronanarbitraryworkspaceusingRefactor>
ApplyScript....
Suchrefactoringscriptscanbeusedindifferentscenariossuchasautomaticfixingof
breakingAPIchangesbetweensoftwarelayersorprovidingpatcheswithrichsemantics.
SafeJARfile WhenexportingaJARfilefromtheworkspace,theJARExportWizardofferstheoption
migration toincluderefactoringinformationintotheJARfile.
UseFile>Export...andselectJARfile.OnthefirstpageoftheJARExportWizard,
selectExportrefactoringsforcheckedprojects.Clickonthelinktoselectthe
refactoringstoinclude.
ClientsarethenabletomigrateanoldversionoftheJARfiletoanewoneusingthe
Refactor>MigrateJARFile...refactoring.Thisrefactoringautomaticallyupdatesall
codewhichisdependentontheoldversionoftheJARfiletousethenewversionofthe
JARfile.
Searching
Locatevariables Youcanlocatevariablesandseetheirread/writestatusbyselectinganidentifier
andtheirread/write (variable,methodortypereferenceordeclaration)andinvokingSearch>Occurrencesin
access File>Identifier.Thismarksallreferencesofthisidentifierinthesamefile.Theresults
arealsoshowninthesearchviewwithdifferentcolorsforreadorwriteaccess,alongwith
iconsshowingthevariable'sreadorwriteaccess.
Alternatively,usetheMarkOccurrencesfeaturetodynamicallyhighlightoccurrences.
Youcansearchoverseveralfilesbyusingthegeneralsearchfeatures(Search>
References).
Searchformethods Tosearchformethodswithaspecificreturntype,use"*<returntype>"asfollows:
withaspecific
returntype OpenthesearchdialogandclickontheJavaSearchtab.
Type'*'andthereturntype,separatedbyaspace,intheSearchstring.
SelecttheCasesensitivecheckbox.
SelectMethodandDeclarationsandthenclickSearch.
Filtersearch Bydefault,JavaSearchfindsreferencesinsideJavacodeandJavadoc.Ifyoudon'twant
matchesinJavadoc toseethereferencesinsideJavadoc,youcanfilterthesematchesbyenabling'Filter
Javadoc'intheviewmenu(trianglesymbol)ofthesearchview.
Filterpotential Potentialmatchesoccurwhenacompiletimeproblempreventsthesearchenginefrom
searchmatches completelyresolvingthematch.FilterthesematcheswithFilterPotentialinthesearch
viewmenu(trianglesymbol).
Tracemethodcall UsetheCallHierarchytofollowlongorcomplexcallchainswithoutlosingtheoriginal
chainswiththeCall context:JustselectamethodandinvokeNavigate>OpenCallHierarchy(Ctrl+Alt+H).
Hierarchy
Youcanalsousedraganddroptoreplacetheviewinputwiththeselectedmethods.
Ctrl+dragaddstheselectedmethodstotheexistingelementsintheview.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 299/322
12/10/2015 Javadevelopmentuserguide
MethodsfromanonymousclassesorspecialtypeslikeRunnablearebydefaultexpanded
withconstructors,sinceitisoftenmoreinterestingtoseewheretheobjectiscreatedthan
wherethemethodisinvoked.ExpandwithConstructorsfromthecontextmenutoggles
thisbehavior.Thedefaultscanbeconfiguredintheviewmenu.
Codenavigationandreading
Openselectionin TherearetwowayshowyoucanopenanelementfromareferenceintheJavaeditor.
Javaeditor
SelectthereferenceinthecodeandpressF3(Navigate>OpenDeclaration)
HoldCtrl,movethemousepointeroverthereference,andclickthehyperlink
HoldingCtrlonanoverridablemethodshowsapopupwithanOpenImplementation
entry,whichdirectlyopenstheimplementationincasethere'sonlyone,orshowsallthe
concreteimplementationsforthatmethodinthehierarchyofitsdeclaringtype,usingthe
quicktypehierarchy.
Thehyperlinkstylenavigationcanbeconfiguredonthe General>Editors>Text
Editors>Hyperlinkingpreferencepage.
Inplaceoutlines PressCtrl+F3intheJavaeditortopopupaninplaceoutlineoftheelementatthecurrent
cursorposition.OrpressCtrl+O(Navigate>QuickOutline)topopupaninplaceoutline
ofthecurrentsourcefile.
Inplaceoutlines PressCtrl+OorCtrl+F3againtoaddinheritedmemberstoanopenInplaceoutline.
showinherited Inheritedmembershaveabluelabel.Filterandsorttheoutlinewiththemenuintheupper
members rightcorner.
TheQuickOutline(Ctrl+O)alsoshowsinheritedmembersofthetypethatcontainsthe
currenteditorselection.Thefocustypesthatcanshowinheritedmembersaremarked
withatriangle( ).
Inplacehierarchy FindoutwhicharethepossiblereceiversofavirtualcallusingtheQuickType
Hierarchy.PlacethecursorinsidethemethodcallandpressCtrl+T(Navigate>Quick
TypeHierarchy).Theviewshowsalltypesthatimplementthemethodwithafullicon.
PressEntertoopenthecorrespondingmethodinaneditor.PressCtrl+Tagaintoswitch
totheSupertypehierarchy.
JavaEditor TheJavaEditorcontainsabreadcrumbnavigationbarwhichshowsthepathtothe
Breadcrumb elementatthecursorposition.ThebreadcrumbcanbeenabledviatheToggle
BreadcrumbtoolbarbuttonorbypressingAlt+Shift+B.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 300/322
12/10/2015 Javadevelopmentuserguide
Eachelementinthebreadcrumbcanbeselectedandactionscanbeinvokedthrougha
contextmenuorkeyboardshortcuts.Furthermorethebreadcrumbletsyounavigateto
otherelementsviadropdowns.
Advanced TheJavaeditorcanhighlightsourcecodeaccordingtoitssemantics(forexample:static
highlighting fields,localvariables,staticmethodinvocations).Havealookatthevariousoptionson
the Java>Editor>SyntaxColoringpreferencepage.
Initiallyfolded Youcanspecifywhichregionsarefoldedbydefaultwhenaneditorisopened.Havea
regions lookatthe Java>Editor>Foldingpreferencepagetocustomizethis.
Differentcolorsareusedtomarkreadandwriteaccesses.
Selectingareturntypeshowsyouthemethod'sexitpoints.Selectanexceptiontosee
whereitisthrown.Selectasuperclassorinterfacetoseethemethodsoverrideor
implementamethodfromtheselectedsupertype.
Finetune'markoccurrences'onthe Java>Editor>MarkOccurrencespreference
page.
Changethecolorfortomarkeronthe General>Editors>TextEditors>
Annotationspreferencepage.
ToshowoccurrencesintheSearchview,usetheSearch>Occurrencesfeature.
Gotonext/ Toquicklynavigatetothenextorpreviousmethodorfield,use
previousmethod Ctrl+Shift+ArrowUp(Navigate>GoTo>PreviousMember)orCtrl+Shift+Arrow
Down(Navigate>GoTo>NextMember)
Controlyour UsetheNext/PreviousAnnotationtoolbarbuttonsorNavigate>NextAnnotation
navigationbetween (Ctrl+.)andNavigate>PreviousAnnotation(Ctrl+,)tonavigatebetweenannotationsin
annotations aJavasourcefile.Withthebuttondropdownmenus,youcanconfigureonwhich
annotationsyouwanttostop:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 301/322
12/10/2015 Javadevelopmentuserguide
Remindersinyour WhenyoutagacommentinJavasourcecodewith"TODO"theJavacompiler
Javacode automaticallycreatesacorrespondingtaskasareminder.Openingthetasknavigatesyou
backtothe"TODO"inthecode.Usethe Java>Compiler>TaskTagspreference
pagetoconfigureanyotherspecialtags(like"FIXME")thatyou'dliketotrackinthetask
list.
Openfrom TheOpenfromClipboarddialog(Navigate>OpenfromClipboard)helpsyounavigate
Clipboarddialog tothematchingJavaelementintheeditor.
ToquicklyfindaJavaelementfromStacktrace,copyalinefromStacktraceandgo
toNavigate>OpenfromClipboard.Forexample:Copy
atjava.lang.String.matches(String.java:1550)anduseOpenfromClipboard
toopenupString.classat1550linenumber.
TricksintheOpen TheOpenTypedialog(Navigate>OpenTypeortoolbarbutton)helpsyounavigatetoa
Typedialog typebyitsname.
Tofindtypesquickly,onlytypethecapitallettersofthetypename:
IOOBEfindsIndexOutOfBoundsException.
Ortypethefirstfewcharactersofeachnamepart:
NuPoiEfindsNullPointerException.
Toseealltypesendingwithagivensuffix,e.g.allTests,use*Test<tonotseeall
typescontainingTestsomewhereelseinthetypename.
Toopenmultipletypesatonce,selecttheminthelistandclickOK.
Makehoverssticky YoucanopenthetextfromahoverinascrollablewindowbypressingF2(Edit>Show
TooltipDescription)orbymovingyourmousepointerintothehover.Youcanselectand
copycontentfromthiswindow,invokeactions,orfollowlinks.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 302/322
12/10/2015 Youcanconfigurehowtoenrichthehoveronthe Javadevelopmentuserguide
General>Editors>TextEditors
preferencepage.
HoversintheJava YoucanseedifferenthoversintheJavaeditorbyusingthemodifierkeys(Shift,Ctrl,
editor Alt).
Whenyoumovethemouseoveranidentifierthathasnowarningorproblemannotationin
theJavaeditor,bydefaultahoverwiththeJavadocextractedfromthecorresponding
sourceofthiselementisshown.Ifthere'saproblemannotationontheidentifierthenthe
hovershowsthecorrespondingmessage.HoldingdowntheShiftkeyshowsyouthe
sourcecode:
Youcanchangethisbehavioranddefinethehoversforothermodifierkeysinthe Java
>Editor>Hoverspreferencepage.
Genericmethod Youcanusehovertoshowtheinferredsignatureofagenericmethod.
inferredsignature
Openandconfigure IfyouwanttoopentheJavadocdocumentationforatype,methodorfieldwithShift+F2
externalJavadoc (Navigate>OpenExternalJavadoc),youfirsthavetospecifythedocumentation
documentation locationstotheelementsparentlibrary(JAR,classfolder)orproject(sourcefolder).
Forlibraries,openthebuildpathpage(Project>Properties>JavaBuildPath),goto
theLibraries,andexpandthenodeofthelibrarywhereyoucaneditthe'Javadoc
location'node.Thedocumentationcanbelocalonyourfilesysteminafolderorarchive,
oronawebserver.
Fortypes,methodsorfieldsinsourcefolders,gotothe(Project>Properties>Javadoc
Location).
Findthemethod Toshowthemethodimplementedbyfunctionalinterfaceinstances,youcanhoveron:
implementedby
functionalinterface ' >'inalambdaexpression
instances
' ::'inamethodreference
Javaviews
Organizing UseTopLevelElements>WorkingSetsinthePackageExplorer'sviewmenuto
workspacewith enableanewmodethatshowsworkingsetsastoplevelelements.Thismodemakesit
manyprojects mucheasiertomanageworkspacescontaininglotsofprojects.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 303/322
12/10/2015 Javadevelopmentuserguide
UseConfigureWorkingSets...fromthePackageExplorer'sviewmenutoconfigure
whichworkingsetsgetshown.ThedialogletsyoucreatenewJavaworkingsets,define
whichworkingsetsareshownandinwhatorder.IfSortWorkingSetsisnotenabled,
workingsetscanalsoberearrangeddirectlyinthePackageExplorerusingdraganddrop.
Assignworking Toassignanelementtoadifferentworkingset,selecttheelementinthePackage
sets ExplorerandchooseAssignWorkingSets...fromthecontextmenu.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 304/322
12/10/2015 Javadevelopmentuserguide
TypeHierarchy Tofindoutwhichtypesinahierarchyoverrideamethod,usethe'ShowMembersin
viewandmethod Hierarchy'feature:
implementations/
definitions 1. SelectthemethodtolookatandpressF4(Navigate>OpenTypeHierarchy).
ThisopenstheTypeHierarchyviewonthemethod'sdeclaringtype.
2. WiththemethodselectedintheTypeHierarchyview,pressthe'LockViewand
ShowMembersinHierarchy'toolbarbutton.
TheTypeHierarchyviewnowshowsonlytypesthatimplementordefinethe'locked'
method.YoucanforexampleseethatisEmpty()isdefinedinListandimplementedin
ArrayListandVectorbutnotinAbstractList.
TypeHierarchy Thetypehierarchymethodviewletsyousorttheselectedtype'smethodsbyitsdefining
viewsupports types.Forexample,forAbstractListyoucanseethatitcontainsmethodsthatwere
groupingby definedinObject,CollectionandList:
definingtype
Tricksinthetype
hierarchy FocusthetypehierarchyonanewtypebypressingF4(Navigate>OpenType
Hierarchy)onanelementoraselectedname.
YoucanopentheTypeHierarchyviewnotonlyontypesbutalsoonpackages,
sourcefolders,JARarchivesandJavaprojects.Youcanselectmultiplepackages,
sourcefolders,orprojects,andthenopenahierarchythatcontainsalltypesinthe
selectedcontainers.
YoucanDrag&DropanelementontotheTypeHierarchyviewtofocusonthat
element.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 305/322
12/10/2015 Javadevelopmentuserguide
Youcanchangetheorientation(fromthedefaultverticaltohorizontal)oftheType
Hierarchyviewfromtheview'stoolbarmenu.
Structuralcompare AstructuralcomparisonofJavasourceignoresthetextualorderofJavaelementslike
ofJavasource methodsandfieldsandshowsmoreclearlywhichelementswerechanged,added,or
removed.
ForinitiatingastructuralcomparisonofJavafilesyouhavetwooptions:
SelecttwoJavacompilationunitsandchooseCompareWith>EachOtherfrom
theview'scontextmenu.Ifthefileshavedifferences,theyareopenedintoa
CompareEditor.ThetoppaneshowsthedifferingJavaelementsdoubleclickingon
oneofthemshowsthesourceoftheelementinthebottompane.
Inanycontextwhereafilecomparisonisinvolved(e.g.aCVSSynchronization)a
doubleclickonaJavafilenotonlyshowsthecontentofthefileinatextcompare
viewer,butitalsoperformsastructuralcompareandopensanewpaneshowingthe
results.
Youcanevenignoreformattingchangeswhenperformingthestructuralcompare:turnon
theIgnoreWhitespaceoptionviatheCompareEditor'stoolbarbutton,oracompare
viewer'scontextmenu.
Structuralcompare AstructuralcomparisonofJavapropertyfiles(extension:.properties)ignoresthetextual
ofpropertyfiles orderofpropertiesandshowswhichpropertieswerechanged,added,orremoved.
Forinitiatingastructuralcomparisonofpropertyfilesyouhavetwooptions:
SelecttwofilesinthePackageExplorerorNavigatorandchooseCompareWith>
EachOtherfromtheview'scontextmenu.
Inanycontextwhereafilecomparisonisinvolved(e.g.aCVSSynchronization)a
doubleclickonapropertyfilenotonlyshowsthecontentofthefileinatext
compareviewer,butitalsoperformsastructuralcompareandopensanewpane
showingtheresults.
Hierarchicalvs.flat AnoptionontheJavaPackages(andPackageExplorer)viewmenuallowsyoutochange
presentationof thewaypackagesaredisplayed.PackagePresentation>Hierarchicaldisplays
packages packagesinatree,withsubpackagesbelowpackagesPackagePresentation>Flat
displaystheminthestandardarrangement,asaflatlistwithallpackagesandsub
packagesassiblings.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 306/322
12/10/2015 Javadevelopmentuserguide
Logicalpackages TheJavaPackagesview(JavaBrowsingperspective)coalescespackagesofthesame
nameacrosssourcefolderswithinaproject.ThescreenshotshowsthePackagesview
containingalogicalpackage.
Compresspackage Ifyourpackagenamesareverylong,youcanconfigureacompressednamethatappears
names intheviewers.Configurationofthecompressionpatternisdoneinthe Java>
Appearancepreferencepage.
Usingthisexample,packagesarerenderedthefollowingway:
Packagename PackagenamesinJavaviewscanbeabbreviatedwithcustomrules.Forexample,the
abbreviations followingrulesproducetherenderingshownbelow:
org.eclipse.ui={UI}
org.eclipse.ui.texteditor={T}
org.eclipse.ui.internal.texteditor=[iT]
Withoutabbreviations: Withabbreviations:
Theabbreviationrulescanbeconfiguredonthe Java>Appearancepreferencepage.
Manipulatingthe InsteadofmanipulatingtheJavaBuildpathonProject>Properties>JavaBuildPath,
Javabuildpath usetheactionsinthePackageExplorer'scontextmenu.
directlyinthe Youcanforexampleaddnewsourcefolders,archivesandlibrariestothebuildpathorin
PackageExplorer andexcludefileandfoldersfromasourcefolder.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 307/322
12/10/2015 Javadevelopmentuserguide
Pastecode YoucanpasteasnippetofcodecontainingaJavatypedirectlyintoapackageorsource
snippetstocreatea foldertocreateanewcompilationunit.Forexample,selectandcopythissourcecode:
type
packagepack
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("HelloWorld")
}
}
ThenselectasourcefolderinthePackageExploreranduseCtrl+V(Edit>Paste).This
automaticallycreatesanewpackage'pack'andfile'HelloWorld.java'withthecopied
content.
YoucanalsopasteamethodorasetofstatementsEclipsewillcreatetherequired
enclosingelementsforyou.
IfyoupastewhilenothingisselectedinthePackageExplorer,Eclipseevencreatesa
newJavaProjectandcreatethe*.javafilethere.Furthermore,theclipboardcanalso
containmultiplepackageandtypedeclarations,inwhichcaseEclipsewillcreateallthe
necessarypackagesand*.javafilesonpaste.
Pastepatchinto What'sthequickestwaytoapplyapatchfromBugzilla?Justopentheattachment,copy
PackageExplorer thepatchtotheclipboardandpasteitintothePackageExplorer.
GroupingJava ConfiguretheProblemsviewtogroupJavaproblemsintocategorieswithGroupby>
problems JavaProblemTypeintheviewmenu.
Youcancontrolifaconfigurableerrorisintendedtobefatalornotatthebottomofthe
Java>Compiler>Errors/Warningspreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 308/322
12/10/2015 Javadevelopmentuserguide
Miscellaneous
Projectspecific Allcodestyleandcompileroptionscanbedefinedperproject.
preferences OpentheprojectpropertypageswithProject>Propertiesonaprojectorusethelinkon
theworkspacepreferences(e.g.the Java>CodeStylepreferencepage)toopena
projectpropertypageandenableprojectspecificsettings.
Theprojectspecificsettingsarestoredinaconfigurationfileinsidetheproject(inthe
'.settings'folder).Whenyoushareaprojectinateam,teammemberswillalsogetthese
projectspecificsettings.
Accessrules AccessrulesgiveyouthepossibilitytoenforceAPIrulesfortypesfromreferenced
libraries.OntheJavabuildpathpage(Project>Properties>JavaBuildPath)editthe
'AccessRules'nodeavailableonreferencedprojects,archives,classfoldersand
libraries.
Packagesortypesinthesereferencescanbeclassifiedas:
Accessible
Discouraged
Forbidden
Accordingtothesettingsonthe Java>Compiler>Errors/Warningspreference
page,thecompilerwillmarkdiscouragedandforbiddenreferenceswithwarningorerrors.
JUnit SelectaJUnittestmethodinaviewandchooseRun>JUnitTestfromthecontext
menuorRun>RunAs>JUnitTestfromthemainmenu.Thiscreatesalaunch
configurationtoruntheselectedtest.
HideJUnitview YoucanconfiguretheJUnitviewtoonlyopenwhenthereareerrorsorfailures.Todoso
untilerrorsor enableActivateonErrors/FailuresonlyintheJUnitviewmenu.Thatway,youcan
failuresoccur havetheviewsetasafastviewandneverlookatitwhentherearenofailingtests.While
therearenoproblemsinyourtestsyouwillseethisicon (thenumberofsmallgreen
squareswillgrow,indicatingprogress)whilerunningthemandthisicon aftertheyare
finished.If,however,errorsorfailuresoccur,theiconwillchangeto (or iftestsare
finished)andtheJUnitviewwillappear.
Contentassistin Contentassist(Ctrl+Space)isalsoavailableininputfieldsofvariousJavadialogs.Look
dialogfields forasmalllightbulbiconbesidethefieldwhenithasfocus.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 309/322
12/10/2015
Smartcaret Javadevelopmentuserguide
TextfieldsforeditingJavanamessupportsmartcaretpositioning.UseCtrl+Leftand
positioningin Ctrl+Righttostopatcamelcaseboundariesinsideaname.UseCtrl+Shift+Leftand
dialogsshowing Ctrl+Shift+Righttoextendtheselectioninsmallsteps.UseCtrl+Deletetodeletethe
Javanames nextandCtrl+Backspacetodeletethepreviouspartofaname.
Ctrl+Right:
Ctrl+Shift+Right:
write"Equal":
Ctrl+Delete:
write"To":
Defineprefixesor Youcanconfiguretheprefixorsuffixforfields,staticfields,parameters,andlocal
suffixesforfields, variables.Thesesettingsonthe Java>CodeStylepreferencepageareusedin
parametersand contentassist,quickfix,andrefactoringwheneveravariablenameiscomputed.
localvariables
OrganizeImports YoucaninvokeSource>OrganizeImportsonsetsofcompilationunits,packages,
worksonmorethan sourcefoldersorJavaprojects.
singlefiles
Organizeimports Eclipsecanautomaticallyorganizeimportswheneveryousaveaneditor.Thisfeaturecan
onsave beenabledgloballyonthe Java>Editor>SaveActionspreferencepage.Thesave
actionscanalsobeconfiguredperproject,whichmakesiteasytoenforceaprojectwide
standardbysharingthesettingsacrossateam:
Besidesorganizingimports,saveactionscanalsoformatcodeandperformotherclean
ups.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 310/322
12/10/2015 Javadevelopmentuserguide
Formatselection SelectmultipleJavafilestoformatandchooseSource>Formattoformatthemall.The
formatactionisalsoavailableonpackages,sourcefoldersorJavaprojects.
IntheJavaEditor,Source>Format(Ctrl+Shift+F)formatsjusttheselectedregion.If
nothingisselected,thewholefilegetsformatted.
Selectexecution WhenyoucreateaJavaprojectthatyouwanttosharewithateam,itisagoodideato
environmentfor useanexecutionenvironmentinsteadofaspecificJRE.
Javaproject
ExecutionenvironmentsaresymbolicrepresentationsofJREswithstandardizedentries
like'J2SE1.4','J2SE1.5'.Thatmeansnofilesystempathwillgointothesharedbuild
path.
JREscanbeassignedtotheenvironmentsonthe Java>InstalledJREs>
ExecutionEnvironmentspreferencepage.
TosetaprojectspecificJREofanexistingproject,opentheproject'sJavaBuildpath
propertypage(Project>Properties>JavaBuildPath),thentheLibrariespage,select
'JRESystemLibrary'andpressEdit.Inthe'EditLibrary'dialogyoucanselecteitheran
ExecutionEnvironment,aprojectspecificJRE,ortheworkspacedefaultJRE.
Usedraganddrop DragandDropisahandyreplacementofEdit>CutandEdit>Paste,orEdit>Copy
andEdit>Paste.HolddowntheCtrlkeywhiledroppingtochangefrommovetocopy.
Importanttoknow:
IfyoumoveJavacompilationunitsbetweenpackagesbyDrag&Drop,thiswill
behavelikearefactoringmoveallmissingimportswillbeaddedandreferences
updated
Ifyoudraganddropsourceelementsliketypesormethods,thiswillonlycopyor
movethecorrespondingsourcecodenoreferenceswillbeupdated
Propagating TheJavacompilercanbeconfiguredtodiagnosedeprecationusingoptionsonthe
deprecationtag Java>Compiler>Errors/Warningspreferencepage.
Usingthisconfiguration,theresultis:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 311/322
12/10/2015 Javadevelopmentuserguide
Ifyou'reunabletofixausageofadeprecatedconstruct,werecommendthatyoutagthe
enclosingmethod,fieldortypeasdeprecated.Thisway,youacknowledgethatyoudid
overrideadeprecatedconstruct,andthedeprecationflagispropagatedtofurther
dependents.
Recoveringfrom Intherareeventofadysfunction,JDTcouldrevealsomeinconsistenciessuchas:
abnormal
inconsistencies missingresultsinaJavaSearchorOpenType
invaliditemsinPackageExplorer
TobringJDTintoaconsistentstateagain,thefollowingactionsneedtobeperformedin
thisexactorder:
1. CloseallprojectsusingnavigatorCloseProjectmenuaction
2. ExitandrestartEclipse
3. OpenallprojectsusingnavigatorOpenProjectmenuaction
4. Manuallytriggeracleanbuildofentireworkspace(Project>Clean...)
IncaseofbuildpatherrorsintheProblemsview,firstlookinthePackageExplorerfor
thisiconsinceitbetterindicateswheretheproblemis.
'*.classwithout The*.classwithoutsourcefiletypeallowstoassociateaninternalorexternaleditorto
source'filetype classfilesthathavenosourceattached.Thise.g.allowstoopentheclassfileina
decompiler:
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 312/322
12/10/2015 Javadevelopmentuserguide
Selectivelyignore YoucanconfigureJDTtoignoreoptionalerrors/warningsfromcertainsourcefolders.See
errors/warnings Projectproperties>JavaBuildPath>Compiler>Source.
fromsourcefolders
WiththisoptionsettoYes,JDTwillsuppresserrors/warningsconfiguredinthe Java
>Compiler>Errors/Warningspreferencepage.Thiscanbedesirableforsourcefolders
thatcontainautogeneratedclassesortests.
Ignoreunavoidable WhenworkingwithJavalibrarieswhoseAPIshavenotbeengenerifiedyet,you
generictype sometimesrunintotypesafetyproblemsthatcannotbeavoidedduetoreferencestoan
problems oldAPIthatusesrawtypes.
SuchproblemscanbeignoredwiththeIgnoreunavoidablegenerictypeproblemsdue
torawAPIscompileroption.
WhentheoldAPIiseventuallygenerified,thenmostoftheseproblemseithergoaway,or
youwillseeacompileerrorbecausethetypeargumentsyouusedarenotcorrect.For
rawreferencesinmethodsignatures,therawtypeproblemwillreappear.
Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>
Errors/Warningspreferencepage.
Debugging
Launchingfrom YoucanrunanddebugJavaapplicationsfromthecontextmenu.Youcanlaunchasource
thecontextmenu file,package,method,type,etc.bychoosingRunAs(orDebugAs)>JavaApplication
fromthecontextmenuinavieworeditor.Alternatively,youcanusetheJavaapplication
launchshortcutkeybinding(Alt+Shift+D,J).ThetoplevelRunAs(orDebugAs)actions
arealsosensitivetothecurrentselectionoractiveeditor.
Evaluationsinthe
debugger Snippetevaluationisavailablefromanumberofplacesinthedebugger.ChoosingDisplay
orInspectfromthecontextmenuoftheeditororVariablesviewwillshowtheresultina
popupwhoseresultcanbesenttotheDisplayorExpressionsviews.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 313/322
12/10/2015 Javadevelopmentuserguide
Viewmanagement TheDebugviewautomaticallymanagesdebugrelatedviewsbasedontheviewselection
innonDebug (displayingJavaviewsforJavastackframesandCviewsforCstackframes,for
perspectives example).Bydefault,thisautomaticviewmanagementonlyoccursintheDebug
perspective,butyoucanenableitforotherperspectivesviatheViewManagement
preferencepageavailablefromtheDebugviewtoolbarpulldown.
Environment YoucanspecifytheenvironmentusedtolaunchJavaapplicationsviatheEnvironment
variables tab.
String VariablesaresupportedformanyparametersofJavaApplicationlaunchconfigurations.
substitutions MostfieldsthatsupportvariableshaveaVariables...buttonnexttothem,suchasthe
programandVMargumentsfields.TheMainTypefieldsupportsvariablesaswellthe
${java_type_name}variableallowsyoutocreateaconfigurationthatwillruntheselected
type.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 314/322
12/10/2015 Javadevelopmentuserguide
Logicalstructures TheLogicalStructurestoggleontheVariablesviewtoolbarpresentsalternatestructures
forcommontypes.JDTprovideslogicalviewsforMaps,Collections,andSWT
Composites.YoucandefinelogicalstructuresforothertypesfromtheLogicalStructures
preferencepage.
Variablecolumns ColumnsintheVariablesviewcanbeconfiguredbyselectingLayout>Select
Columns...intheviewmenu.Adialogallowsyoutoselectthecolumnstodisplay.For
example,acolumncanbeaddedtodisplayinstancecountsofclasses(whendebugging
withJavaSE1.6).Columnscanbetoggledon/offusingtheLayout>ShowColumns
action.
Showreferences WhendebuggingwithJavaSE1.6,referencestoobjectscanbedisplayedintheVariables
viewbyselectingJava>ShowReferencesintheviewmenu.A"referencedfrom"entry
willappearundereachobjectthatcanbeexpandedtoshowallreferencestothatobject.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 315/322
12/10/2015
Allinstances Javadevelopmentuserguide
WhendebuggingwithJavaSE1.6,allinstancesofaclasscanbeinspectedbyselectinga
classinaneditoroutline,variablesview,compilationunitorclassfileeditorandinvoking
AllInstances...fromthecontextmenu.Apopupdialogwilldisplayallinstancesofthe
selectedclass.
DefaultVM IfyouspecifythesameargumentstoacertainVMfrequently,youcanconfigureDefault
arguments VMArgumentsintheInstalledJREspreferencepage.Thisismoreconvenientthan
specifyingthemforeachlaunchconfiguration.
Stopinmain YoucanuseStopinmaininaJavaApplicationlaunchconfigurationtocauseyour
programtostopatthefirstexecutablelineofthemainmethodwhenyourunitunderdebug
mode.
Conditional YoucanuseexpressionstodefineconditionalbreakpointsusingtheBreakpoint
breakpoints Properties...dialogordetailpaneinthebreakpointsview.Aconditioncontrolswhena
breakpointactuallyhaltsexecution.Youcanspecifywhetheryouwantthebreakpointto
suspendexecutiononlywhentheconditionistrue,orwhentheconditionvaluechanges.
Thebreakpointconditioneditorsupportscontentassist.
Debuggingby YoucanavoidinsertingSystem.out.println()statementsinyourcodefordebuggingby
writingtoconsole usingconditionalbreakpointstoprinttotheConsoleview.Todoso,setaconditional
breakpointwithSuspendwhen'true'optionandaconditionwhichisalwaysfalse,e.g.
Disabling Ifyoufindyourselffrequentlyaddingandremovingabreakpointinthesameplace,consider
breakpoints disablingthebreakpointwhenyoudon'tneeditandenablingitwhenneededagain.This
canbedoneusingDisableBreakpointinthebreakpointcontextmenuorbyunchecking
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 316/322
12/10/2015 thebreakpointintheBreakpointsview. Javadevelopmentuserguide
YoucanalsotemporarilydisableallbreakpointsusingtheSkipAllBreakpoints
(Ctrl+Alt+B)actionintheBreakpointsviewtoolbar.Thiswilltellthedebuggertoskipall
breakpointswhilemaintainingtheircurrentenabledstate.
Togglebreakpoint UsemodifierkeyswhiletogglingbreakpointsintheJavaeditor:
modifierkeys
HoldingtheCtrlkeywhiledoubleclicking(toggling)abreakpointwillcausethe
Propertiesdialogforthatbreakpointtobedisplayed(ontheMac,useCommand)
HoldingtheShiftkeywhiledoubleclicking(toggling)abreakpointwillenable/
disablethatbreakpoint
Ifthereisnoexistingbreakpoint,anormalbreakpointtoggletakesplaceevenifamodifier
keyishelddown.
Changingvariable Whenathreadissuspendedinthedebugger,youcanchangethevaluesofJavaprimitives
values andStringsintheVariablesview.Fromthevariable'scontextmenu,chooseChange
VariableValue.YoucanalsochangethevaluebytypinganewvalueintotheDetailspane
andusingtheAssignValueactioninthecontextmenu(CTRL+Skeybinding).
Variablevaluesin WhenathreadissuspendedandthecursorisplacedoveravariableintheJavaeditor,the
hoverhelp valueofthatvariableisdisplayedashoverhelp.
Droptoframe Whensteppingthroughyourcode,youmightoccasionallysteptoofar,orstepoveraline
youmeanttostepinto.Ratherthanrestartingyourdebugsession,youcanusetheDrop
toFrameactiontoquicklygobacktothebeginningofamethod.Selectthestackframe
correspondingtotheJavamethodyouwishtorestart,andselectDroptoFramefrom
Debugviewtoolbarorthestackframe'scontextmenu.Thecurrentinstructionpointerwill
beresettothefirstexecutablestatementinthemethod.Thisworksfornontopstack
framesaswell.
NotethatDroptoframeisonlyavailablewhendebuggingwitha1.4orhigherVM,ortheJ9
VM.TherearesomesituationswhereaJVMmaybeunabletopopthedesiredframesfrom
thestack.Forexample,itisgenerallyimpossibletodroptothebottomframeofthestack
ortoanyframebelowanativemethod.
Hotcodereplace ThedebuggersupportsHotCodeReplacewhendebuggingwitha1.4orhigherVM,orthe
J9VM.Thisletsyoumakechangestocodeyouarecurrentlydebugging.Notethatsome
changessuchasnewordeletedmethods,classvariablesorinnerclassescannotbehot
swapped,dependingonthesupportprovidedbyaparticularVM.
Steppinginto TheJavadebuggerallowsyoutostepintoasinglemethodwithinaseriesofchainedor
selectionsand nestedmethodcalls.SimplyselectthemethodyouwishtostepintoandselectStepinto
hyperlink SelectionfromtheJavaeditorcontextmenu.
debugging
Thisfeatureworksinplacesotherthanthecurrentlyexecutingline.Trydebuggingtoa
breakpointandstepintoamethodafewlinesbelowthecurrentinstructionpointer.
Whenthecaretisnotinamethodname,thefeaturestepsintothenextmethodonthe
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 317/322
12/10/2015 Javadevelopmentuserguide
selectedline.Forexample,whenthecaretisatthebeginningoftheline
assertTrue(fFull.size()==100),
thenStepintoSelectionstepsintoassertTrue(..)(unlikeStepInto,whichwouldstep
intosize()).
Youcanalsostepintoamethodbyusinghyperlinknavigation.Simplyplacethecursor
overthemethodyouwishtostepintoanduseCtrl+Alt+Clicktostepintothemethod
(ratherthanCtrl+Clickwhichwillnavigatetothesourcecode).
Consolepinand OutputdisplayedintheconsolecanbelockedtoaspecificprocessviathePinConsole
lock actionintheConsoleviewtoolbar.There'salsoaScrollLockactionthatstopsthe
consolefromscrollingasnewoutputisappended.
Creatingwatch AwatchitemisanexpressionintheExpressionsviewwhosevalueisupdatedasyou
items debug.YoucancreatewatchitemsfromtheJavaeditorbyselectinganexpressionor
variableandchoosingWatchfromitscontextmenuorthetoplevelRunmenu.
Watchpoints Awatchpointisabreakpointthatsuspendsexecutionwheneveraspecifiedfieldis
accessedormodified.Tosetawatchpoint,selectafieldintheOutlineviewandchoose
ToggleWatchpointfromitscontextmenu.Toconfigureawatchpoint,selectthe
watchpointintheBreakpointsviewandchooseProperties...fromitscontextmenu.The
mostimportantpropertiesforthistypeofbreakpointaretheAccessandModification
checkboxeswhichcontrolwhenthebreakpointcansuspendexecution.
Classload Aclassloadbreakpointsuspendsexecutionwhenaspecifiedclassisloadedinthevirtual
breakpoints machine.Tosetaclassloadbreakpoint,selectaclassintheOutlineviewandchoose
ToggleClassLoadBreakpointfromitscontextmenu.YoucanalsousetheRun>Add
ClassLoadBreakpoint...menuactiontocreateaclassloadbreakpoint.
Method Amethodbreakpointsuspendsexecutionwhenaspecificmethodisenteredorexited.To
breakpoints setamethodbreakpoint,selectamethodintheOutlineviewandchooseToggleMethod
Breakpointfromitscontextmenu.Alternatively,doubleclickonamethoddeclarationline
intheeditorrulerorusetheRun>ToggleMethodBreakpointmenuactiontocreatea
methodbreakpointinthecurrentlyselectedmethod.
Bydefaultamethodbreakpointonlysuspendsexecutionwhenamethodisentered.You
canusethebreakpointdetailpaneorthebreakpointpropertiesdialogtoconfigurethe
breakpointtosuspendonexit.Methodbreakpointsalsosupportconditions.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 318/322
12/10/2015 Javadevelopmentuserguide
Threadsand TheJavadebuggeroptionallydisplaysmonitorinformationintheDebugview.Usethe
monitors ShowMonitorsactionintheDebugviewdropdownmenutoshowwhichthreadsare
holdinglocksandwhicharewaitingtoacquirelocks.Threadsinvolvedinadeadlockare
renderedinred.
Stepfilters Stepfilterspreventthedebuggerfromsuspendinginspecifiedclassesandpackageswhen
steppingintocode.Stepfiltersareestablishedwiththe Java>Debug>StepFiltering
preferencepage.WhentheUseStepFilterstoggle(onthedebugtoolbarandmenu)ison,
stepfiltersareappliedtoallstepactions.IntheDebugview,theselectedstackframe's
packageordeclaringtypecanbequicklyaddedtothelistoffiltersbyselectingFilterType
orFilterPackagefromthestackframe'scontextmenu.
Usingthe IfyouwanttoexperimentwithAPIortestoutanewalgorithm,it'sfrequentlyeasiertouse
scrapbook aJavascrapbookpagethancreateanewclass.Ascrapbookpageisacontainerfor
randomsnippetsofcodethatyoucanexecuteatanytimewithoutacontext.Tocreatea
scrapbookpage,createanewfilewitha.jpageextension(orusethe NewScrapbook
Pagewizard).Enterwhatevercodeyouwishtoexecuteandthenselectit.Therearethree
waystoexecuteyourcode:
Executetheselectedcodeandplacethereturnedresultinaninspectpopup
ExecutetheselectedcodeandplacetheStringresultrightinthescrapbookpage
Executetheselectedcode(andignoreanyreturnedresult)
Theseactionsareintheworkbenchtoolbarandalsointhescrapbookpage'scontextmenu.
Editing HoldingdowntheCtrlkeyandmakingaselectionfromtheRunorDebugdropdown
launch menuopenstheassociatedlaunchconfigurationforediting.Thelaunchconfigurationcan
configurations alsobeopenedfromthecontextmenuassociatedwithanyitemintheDebugview.
Favoritelaunch LaunchconfigurationsappearintheRun/Debugdropdownmenusinmostrecently
configurations launchedorder.Howeveritispossibletoforcealaunchconfigurationtoalwaysappearat
thetopofthedropdownsbymakingtheconfigurationa'favorite'.UsetheOrganize
Favorites...actionfromtheappropriatedropdownmenutoconfigureyourfavoritelaunch
configurations.
Detailformatters IntheVariables&Expressionsviews,thedetailpaneshowsanexpandedrepresentation
ofthecurrentlyselectedvariable.Bydefault,thisexpandedrepresentationistheresultof
callingtoString()ontheselectedobject,butyoucancreateacustomdetailformatter
thatwillbeusedinsteadbychoosingNewDetailFormatterfromthevariable'scontext
menu.Thisdetailformatterwillbeusedforallobjectsofthesametype.Youcanviewand
editalldetailformattersinthe Java>Debug>DetailFormatterspreferencepage.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 319/322
12/10/2015 Javadevelopmentuserguide
Runningcode Youcanrunanddebugcodethatdidnotcompilecleanly.Theonlydifferencebetween
withcompile runningcodewithandwithoutcompileerrorsisthatifalineofcodewithacompileerroris
errors executed,oneoftwothingswillhappen:
Ifthe'Suspendexecutiononcompilationerrors'preferenceonthe Java>Debug
preferencepageissetandyouaredebugging,thedebugsessionwillsuspendasifa
breakpointhadbeenhit.NotethatifyourVMsupportsHotCodeReplace,youcould
thenfixthecompilationerrorandresumedebugging
Otherwise,executionwillterminatewitha'unresolvedcompilation'error
Itisimportanttoemphasizethataslongasyourexecutionpathavoidslinesofcodewith
compileerrors,youcanrunanddebugjustasyounormallydo.
Wordwrapin Thedetailsareaofthedebugger'sVariablesandExpressionsviewssupportswordwrap,
Variablesview availablefromtheviewdropdownmenu.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 320/322
12/10/2015 Javadevelopmentuserguide
Codeassistinthe CodeassistisavailableinmanycontextsbeyondwritingcodeintheJavaeditor:
debugger
Whenenteringabreakpointcondition
IntheDetailspaneoftheVariables&Expressionsview
WhenenteringaDetailFormattercodesnippet
WhenenteringaLogicalStructurecodesnippet
WhenenteringcodeinaScrapbookpage
IntheDisplayview
Commandline Youcanalwaysseetheexactcommandlineusedtolaunchaprograminrunordebug
details modebyselectingPropertiesfromthecontextmenuofaprocessordebugtarget,evenif
thelaunchhasterminated.
Stacktrace Javastacktracesintheconsoleappearwithhyperlinks.Whenyouplacethemouseovera
hyperlinks lineinastacktracethepointerchangestothehand.Pressingthemousebuttonopensthe
associatedJavasourcefileandpositionsthecursoratthecorrespondingline.Pressingthe
mousebuttonontheexceptionnameatthetopofthestacktracewillcreateanexception
breakpoint.
Debugginginthe YoucandebugintheJavaperspectivebyconfiguringtheRun/Debug>View
Javaperspective Managementpreferences.Selecttheperspectivesyouwanttobedebugfrom.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 321/322
12/10/2015 Javadevelopmentuserguide
Ensurethepreferencetoactivatethedebugviewwhenabreakpointishitisturnedon(via
thetoplevelRun/Debugpreferencepage).
YoucandisabletheperspectiveswitchingpromptontheRun/Debug>Perspectives
preferencepage.WiththesesettingstheDebugviewwillautomaticallyopenintheJava
perspectivewhenabreakpointishit.
ByplacingtheDebugviewatthetopoftheperspectiveandresizingitsheighttothesize
ofoneelement,theviewwillswitchtoabreadcrumbpresentation.Thisminimizesthe
amountofscreenspacetheviewconsumes.
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 322/322