Skip to main content

Java

info

You can enable the extra with the :LazyExtras command. Plugins marked as optional will only be configured if they are installed.

Alternatively, you can add it to your lazy.nvim imports
lua/config/lazy.lua
require("lazy").setup({
spec = {
{ "LazyVim/LazyVim", import = "lazyvim.plugins" },
{ import = "lazyvim.plugins.extras.lang.java" },
{ import = "plugins" },
},
})

Below you can find a list of included plugins and their default settings.

caution

You don't need to copy the default settings to your config. They are only shown here for reference.

nvim-treesitter

Add java to treesitter.

opts = function(_, opts)
opts.ensure_installed = opts.ensure_installed or {}
vim.list_extend(opts.ensure_installed, { "java" })
end

mason.nvim

opts = function(_, opts)
opts.ensure_installed = opts.ensure_installed or {}
vim.list_extend(opts.ensure_installed, { "java-test", "java-debug-adapter" })
end

nvim-lspconfig

Configure nvim-lspconfig to install the server automatically via mason, but defer actually starting it to our configuration of nvim-jtdls below.

opts = {
-- make sure mason installs the server
servers = {
jdtls = {},
},
setup = {
jdtls = function()
return true -- avoid duplicate servers
end,
},
}

nvim-jdtls

Set up nvim-jdtls to attach to java files.

opts = function()
return {
-- How to find the root dir for a given filename. The default comes from
-- lspconfig which provides a function specifically for java projects.
root_dir = require("lspconfig.server_configurations.jdtls").default_config.root_dir,

-- How to find the project name for a given root dir.
project_name = function(root_dir)
return root_dir and vim.fs.basename(root_dir)
end,

-- Where are the config and workspace dirs for a project?
jdtls_config_dir = function(project_name)
return vim.fn.stdpath("cache") .. "/jdtls/" .. project_name .. "/config"
end,
jdtls_workspace_dir = function(project_name)
return vim.fn.stdpath("cache") .. "/jdtls/" .. project_name .. "/workspace"
end,

-- How to run jdtls. This can be overridden to a full java command-line
-- if the Python wrapper script doesn't suffice.
cmd = { vim.fn.exepath("jdtls") },
full_cmd = function(opts)
local fname = vim.api.nvim_buf_get_name(0)
local root_dir = opts.root_dir(fname)
local project_name = opts.project_name(root_dir)
local cmd = vim.deepcopy(opts.cmd)
if project_name then
vim.list_extend(cmd, {
"-configuration",
opts.jdtls_config_dir(project_name),
"-data",
opts.jdtls_workspace_dir(project_name),
})
end
return cmd
end,

-- These depend on nvim-dap, but can additionally be disabled by setting false here.
dap = { hotcodereplace = "auto", config_overrides = {} },
dap_main = {},
test = true,
}
end

which-key.nvim

opts = nil

nvim-dap (optional)

Ensure java debugger and test packages are installed.

opts = nil