How to access eclipse workspace?

本文介绍了在Eclipse插件开发中如何访问Eclipse工作区,包括编程方式调用Ant命令及获取当前项目的具体方法。提供了详细的代码示例,帮助开发者更好地理解并实践。

摘要:

   在开发eclipse pluin的时候,某些情况下我们需要访问eclipse workspace,例如:在插件中以编程的方式调用ant命令、访问eclipse workspace中的project等。一次在网上偶遇到本文的原创者kobye,此人正在进行jsports项目的开发,对此颇有心地,故在此行文与 众人共同探讨之。

一、基础工作-在插件中以编程的方式调用ant命令:

   在开发eclipse pluin的时候,某些情况下我们需要访问eclipse workspace,例如:在插件中以编程的方式调用ant命令等。

   如何做到这一点?

 public void execute(){
     IWorkspace ws = ResourcesPlugin.getWorkspace();
     IProject[] ps = ws.getRoot().getProjects();
     System.out.println(ws.getRoot().getFullPath().makeAbsolute().toOSString());

     for(int i=0;i<ps.length;i++){
         IProject p = ps[i];
         IPath location = p.getLocation();
         IFile ifile = p.getFile("build.xml");
         System.out.println(ifile.getLocation().toFile().getAbsolutePath());      
         File f =  new File(ifile.getLocation().toFile().getAbsolutePath());
         if(!f.exists()){
             continue;
         }
         Project pro = new Project();        
         pro.setBasedir(location.toFile().getAbsolutePath());
         pro.init();
         ProjectHelper helper = ProjectHelper.getProjectHelper();
         helper.parse(pro, f);
         Hashtable tars = pro.getTargets();
         System.out.println("name==="+name);
         Target t = (Target) tars.get(name);
         if(t==null){
             return;
         }
         DefaultLogger consoleLogger = new DefaultLogger();
         consoleLogger.setErrorPrintStream(System.err);
         consoleLogger.setOutputPrintStream(System.out);
         consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
         pro.addBuildListener(consoleLogger);   
         pro.executeTarget(this.name);
         break;
     }
    
 }



以上代码(单独编译不会通过,请把 name换位ant 的target)可以放到插件的代码中。

以上代码的含义:

     获得eclipse workspace的引用,对workspace下的pronjects进行循环,如果该project下有build.xml并且该文件中有name的 target那么就以ant的方式调用,并把ant运行的输出输出到eclipse的console。

二、如何访问current project

   上一节给出来在eclipse plugin 中访问eclipse workspace, 从而访问该workspace下所有project的方案,WorkSpace以及相关的类不提供直接访问current project的方法,所以只能走其他途径.

    在我们的plugin中,我们要提供界面入口,比如 PopMenu  ActionMenu 等之类的,
这些界面入口是要实现一些接口的,例如:PopMenu要实现IObjectActionDelegate,
这个接口有几个方法,其中 public void selectionChanged(IAction action, Iselection
selection) ;

这个方法很早重要,可以通过Iselection获得当前选择中的Project.

Iselection共有三个子接口,分别对应三个实现类,那么通过判断Iselection的实际类型可以获得其子接口的引用,
然后对其遍历,通过getAdaptor方法获得所有的选择的IResource的引用,
再进一步对IResource进行类型识别,得到IResource.PROJECT类型的元素即为IProject的引用.

下面是程序:

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.Iselection;
import org.eclipse.jface.viewers.IStructuredselection;

import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

/**
 * @author Kobye
 */
public class TestPopMenu implements IObjectActionDelegate {
   private IStructuredselection selection;



 /**
 * Constructor for Action1.
 */
 public TestPopMenu () {
 super();
 }

 /**
 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
 */
 public void setActivePart(IAction action, IWorkbenchPart targetPart) {

 }

 /**
 * @see IActionDelegate#run(IAction)
 */
 public void run(IAction action) {
 Shell shell = new Shell();
 MessageDialog.openInformation(
  shell,
  "Pop Plug-in",
  "New Action was executed.");

 }

 public static Object getAdapter(Object adaptable, Class c) {
 if (c.isInstance(adaptable)) {
  return adaptable;
 }
 if (adaptable instanceof IAdaptable) {
  IAdaptable a = (IAdaptable) adaptable;
  Object adapter = a.getAdapter(c);
  if (c.isInstance(adapter)) {
   return adapter;
  }
 }
 return null;
 }


 /***
 * 这个方法和下面的方法很重要。
 * @param selection
 * @param c
 * @return
 */
 private Object[] getselectedResources(IStructuredselection selection,Class c) {
 return getselectedAdaptables(selection, c);
 }

 private static Object[] getselectedAdaptables(Iselection selection, Class c) {
 ArrayList result = null;
 if (!selection.isEmpty()) {
  result = new ArrayList();
  Iterator elements = ((IStructuredselection) selection).iterator();
  while (elements.hasNext()) {
   Object adapter = getAdapter(elements.next(), c);
   if (c.isInstance(adapter)) {
    result.add(adapter);
   }
  }
 }
 if (result != null && !result.isEmpty()) {
  return result.toArray((Object[])Array.newInstance(c, result.size()));
 }
 return (Object[])Array.newInstance(c, 0);
 }


 /**
 * 这个方法保存了Iselection的引用,
 * 请注意:Iselection的实际类型因不同的应用,其实际类型可能不同,
 * 共有三种可能,请查阅eclipse API。
 *
 * @see IActionDelegate#selectionChanged(IAction, Iselection)
 */
 public void selectionChanged(IAction action, Iselection selection) {
    this.selection = (IStructuredselection) selection;
    System.out.println("current project name==="+this.getProject().getName());
 }

 /**
 * 这个方法可以得到current project。
 *
 * @return
 */
 private IProject getProject(){
    IResource[]rs =
(IResource[])getselectedResources((IStructuredselection)selection,IResource.class);
    IProject project = null;
    for(int i =0;i<rs.length;i++){
        IResource r = rs[i];
        if(r.getType()==IResource.PROJECT){
            project = (IProject) r;
            break;
        }
    }
    return project;
 }
}
<!-- bottom ads -->
Language support for Java ™ for Visual Studio Code Visual Studio Marketplace Installs Join the chat at https://gitter.im/redhat-developer/vscode-java Build Status License Provides Java ™ language support via Eclipse ™ JDT Language Server, which utilizes Eclipse ™ JDT, M2Eclipse and Buildship. Quick Start Install the Extension On the following platforms, the extension should activate without any setup : win32-x64, darwin-x64, darwin-arm64, linux-x64, linux-arm64. If on another platform, or using the "universal" version, you can set a Java Development Kit. It must be Java 21 or above. Optionally, download and install a Java Development Kit for your project (Java 1.8 or above is supported). See Project JDKs for more details Extension is activated when you first access a Java file Recognizes projects with Maven or Gradle build files in the directory hierarchy. Features screencast Supports code from Java 1.8 to Java 24 Maven pom.xml project support Gradle project support (with experimental Android project import support) Standalone Java files support As-you-type reporting of parsing and compilation errors Code completion Code/Source actions / Refactoring Javadoc hovers Organize imports triggered manually or on save when pasting code into a java file with Ctrl+Shift+v (Cmd+Shift+v on Mac). Type search Code outline Code folding Code navigation Code lens (references/implementations) Highlights Code formatting (on-type/selection/file) Code snippets Annotation processing support (automatic for Maven projects) Semantic selection Diagnostic tags Call Hierarchy Type Hierarchy To launch and debug your Java programs, it's recommended you install Java Debug Extension for Visual Studio Code. See the changelog for the latest release. You might also find useful information in the project Wiki. Setting the JDK Java Tooling JDK Now that Java extension will publish platform specific versions, it will embed a JRE for supported platforms such as win32-x64, linux-x64, linux-arm64, darwin-x64, darwin-arm64. The embedded JRE is used to launch the Language Server for Java. Users are only responsible for configuring Project JDKs to compile your Java projects. The following part is only kept for the universal version without embedded JRE. The tooling JDK will be used to launch the Language Server for Java. And by default, will also be used to compile your projects. Java 21 is the minimum required version. The path to the Java Development Kit can be specified by the java.jdt.ls.java.home setting in VS Code settings (workspace/user settings). If not specified, it is searched in the following order until a JDK meets current minimum requirement. the JDK_HOME environment variable the JAVA_HOME environment variable on the current system path Project JDKs If you need to compile your projects against a different JDK version, it's recommended you configure the java.configuration.runtimes property in your user settings, eg: "java.configuration.runtimes": [ { "name": "JavaSE-1.8", "path": "/path/to/jdk-8", }, { "name": "JavaSE-11", "path": "/path/to/jdk-11", }, { "name": "JavaSE-24", "path": "/path/to/jdk-24", "default": true }, ] The default runtime will be used when you open standalone Java files. Available commands The following commands are available: Switch to Standard Mode: switches the Java Language Server to Standard mode. This command is only available when the Java Language Server is in LightWeight mode. Java: Reload Projects (Shift+Alt+U): It forces project configuration / classpath updates (eg. dependency changes or Java compilation level), according to the project build descriptor. Java: Import Java Projects into Workspace: detects and imports all the Java projects into the Java Language Server workspace. Java: Open Java Language Server Log File: opens the Java Language Server log file, useful for troubleshooting problems. Java: Open Java Extension Log File: opens the Java extension log file, useful for troubleshooting problems. Java: Open All Log Files: opens both the Java Language Server log file and the Java extension log file. Java: Force Java Compilation (Shift+Alt+B): manually triggers compilation of the workspace. Java: Rebuild Projects: manually triggers a full build of the selected projects. Java: Open Java Formatter Settings: opens the Eclipse formatter settings. Creates a new settings file if none exists. Java: Clean Java Language Server Workspace: cleans the Java language server workspace. Java: Attach Source: attaches a jar/zip source to the currently opened binary class file. This command is only available in the editor context menu. Java: Add Folder to Java Source Path: adds the selected folder to its project source path. This command is only available in the file explorer context menu and only works for unmanaged folders. Java: Remove Folder from Java Source Path: removes the selected folder from its project source path. This command is only available in the file explorer context menu and only works for unmanaged folders. Java: List All Java Source Paths: lists all the Java source paths recognized by the Java Language Server workspace. Java: Show Build Job Status: shows the Java Language Server job status in Visual Studio Code terminal. Java: Go to Super Implementation: goes to the super implementation for the current selected symbol in editor. Java: Restart Java Language Server: restarts the Java language server. Supported VS Code settings The following settings are supported: java.home : Deprecated, please use 'java.jdt.ls.java.home' instead. Absolute path to JDK home folder used to launch the Java Language Server. Requires VS Code restart. java.jdt.ls.lombokSupport.enabled: Whether to enable lombok support. Defaults to true. java.jdt.ls.vmargs : Extra VM arguments used to launch the Java Language Server. Requires VS Code restart. java.errors.incompleteClasspath.severity : Specifies the severity of the message when the classpath is incomplete for a Java file. Supported values are ignore, info, warning, error. java.trace.server : Traces the communication between VS Code and the Java language server. java.configuration.updateBuildConfiguration : Specifies how modifications on build files update the Java classpath/configuration. Supported values are disabled (nothing happens), interactive (asks about updating on every modification), automatic (updating is automatically triggered). java.configuration.maven.userSettings : Path to Maven's user settings.xml. java.configuration.checkProjectSettingsExclusions: Deprecated, please use 'java.import.generatesMetadataFilesAtProjectRoot' to control whether to generate the project metadata files at the project root. And use 'files.exclude' to control whether to hide the project metadata files from the file explorer. Controls whether to exclude extension-generated project settings files (.project, .classpath, .factorypath, .settings/) from the file explorer. Defaults to false. java.referencesCodeLens.enabled : Enable/disable the references code lenses. java.implementationCodeLens : Enable/disable the implementations code lens for the provided categories. java.signatureHelp.enabled : Enable/disable signature help support (triggered on (). java.signatureHelp.description.enabled : Enable/disable to show the description in signature help. Defaults to false. java.contentProvider.preferred : Preferred content provider (see 3rd party decompilers available in vscode-java-decompiler). java.import.exclusions : Exclude folders from import via glob patterns. Use ! to negate patterns to allow subfolders imports. You have to include a parent directory. The order is important. java.import.gradle.enabled : Enable/disable the Gradle importer. Specify the Gradle distribution used by the Java extension: java.import.gradle.wrapper.enabled: Use Gradle from the 'gradle-wrapper.properties' file. Defaults to true. java.import.gradle.version: Use Gradle from the specific version if the Gradle wrapper is missing or disabled. java.import.gradle.home: Use Gradle from the specified local installation directory or GRADLE_HOME if the Gradle wrapper is missing or disabled and no 'java.import.gradle.version' is specified. java.import.gradle.arguments: Arguments to pass to Gradle. java.import.gradle.jvmArguments: JVM arguments to pass to Gradle. java.import.gradle.user.home: setting for GRADLE_USER_HOME. java.import.gradle.offline.enabled: Enable/disable the Gradle offline mode. Defaults to false. java.import.maven.enabled : Enable/disable the Maven importer. java.autobuild.enabled : Enable/disable the 'auto build'. java.maxConcurrentBuilds: Set max simultaneous project builds. java.completion.enabled : Enable/disable code completion support. java.completion.guessMethodArguments : Specify how the arguments will be filled during completion. Defaults to auto. auto: Use off only when using Visual Studio Code - Insiders, other platform will defaults to insertBestGuessedArguments. off: Method arguments will not be inserted during completion. insertParameterNames: The parameter names will be inserted during completion. insertBestGuessedArguments: The best guessed arguments will be inserted during completion according to the code context. java.completion.filteredTypes: Defines the type filters. All types whose fully qualified name matches the selected filter strings will be ignored in content assist or quick fix proposals and when organizing imports. For example 'java.awt.*' will hide all types from the awt packages. java.completion.favoriteStaticMembers : Defines a list of static members or types with static members. java.completion.importOrder : Defines the sorting order of import statements. java.format.enabled : Enable/disable the default Java formatter. java.format.settings.url : Specifies the url or file path to the Eclipse formatter xml settings. java.format.settings.profile : Optional formatter profile name from the Eclipse formatter settings. java.format.comments.enabled : Includes the comments during code formatting. java.format.onType.enabled : Enable/disable on-type formatting (triggered on ;, } or <return>). java.foldingRange.enabled: Enable/disable smart folding range support. If disabled, it will use the default indentation-based folding range provided by VS Code. java.maven.downloadSources: Enable/disable download of Maven source artifacts as part of importing Maven projects. java.maven.updateSnapshots: Force update of Snapshots/Releases. Defaults to false. java.codeGeneration.hashCodeEquals.useInstanceof: Use 'instanceof' to compare types when generating the hashCode and equals methods. Defaults to false. java.codeGeneration.hashCodeEquals.useJava7Objects: Use Objects.hash and Objects.equals when generating the hashCode and equals methods. This setting only applies to Java 7 and higher. Defaults to false. java.codeGeneration.useBlocks: Use blocks in 'if' statements when generating the methods. Defaults to false. java.codeGeneration.generateComments: Generate method comments when generating the methods. Defaults to false. java.codeGeneration.toString.template: The template for generating the toString method. Defaults to ${object.className} [${member.name()}=${member.value}, ${otherMembers}]. java.codeGeneration.toString.codeStyle: The code style for generating the toString method. Defaults to STRING_CONCATENATION. java.codeGeneration.toString.skipNullValues: Skip null values when generating the toString method. Defaults to false. java.codeGeneration.toString.listArrayContents: List contents of arrays instead of using native toString(). Defaults to true. java.codeGeneration.toString.limitElements: Limit number of items in arrays/collections/maps to list, if 0 then list all. Defaults to 0. java.selectionRange.enabled: Enable/disable Smart Selection support for Java. Disabling this option will not affect the VS Code built-in word-based and bracket-based smart selection. java.showBuildStatusOnStart.enabled: Automatically show build status on startup, defaults to notification. notification: Show the build status via progress notification. terminal: Show the build status via terminal. off: Do not show any build status. For backward compatibility, this setting also accepts boolean value, where true has the same meaning as notification and false has the same meaning as off. java.project.outputPath: A relative path to the workspace where stores the compiled output. Only effective in the WORKSPACE scope. The setting will NOT affect Maven or Gradle project. java.project.referencedLibraries: Configure glob patterns for referencing local libraries to a Java project. java.completion.maxResults: Maximum number of completion results (not including snippets). 0 (the default value) disables the limit, all results are returned. In case of performance problems, consider setting a sensible limit. java.configuration.runtimes: Map Java Execution Environments to local JDKs. java.server.launchMode: Standard: Provides full features such as intellisense, refactoring, building, Maven/Gradle support etc. LightWeight: Starts a syntax server with lower start-up cost. Only provides syntax features such as outline, navigation, javadoc, syntax errors. The lightweight mode won't load thirdparty extensions, such as java test runner, java debugger, etc. Hybrid: Provides full features with better responsiveness. It starts a standard language server and a secondary syntax server. The syntax server provides syntax features until the standard server is ready. And the syntax server will be shutdown automatically after the standard server is fully ready. Default launch mode is Hybrid. Legacy mode is Standard java.sources.organizeImports.starThreshold: Specifies the number of imports added before a star-import declaration is used, default is 99. java.sources.organizeImports.staticStarThreshold: Specifies the number of static imports added before a star-import declaration is used, default is 99. java.imports.gradle.wrapper.checksums: Defines allowed/disallowed SHA-256 checksums of Gradle Wrappers. java.project.importOnFirstTimeStartup: Specifies whether to import the Java projects, when opening the folder in Hybrid mode for the first time. Supported values are disabled (never imports), interactive (asks to import or not), automatic (always imports). Default to automatic. java.project.importHint: Enable/disable the server-mode switch information, when Java projects import is skipped on startup. Defaults to true. java.import.gradle.java.home: Specifies the location to the JVM used to run the Gradle daemon. java.project.resourceFilters: Excludes files and folders from being refreshed by the Java Language Server, which can improve the overall performance. For example, ["node_modules",".git"] will exclude all files and folders named 'node_modules' or '.git'. Pattern expressions must be compatible with java.util.regex.Pattern. Defaults to ["node_modules",".git"]. java.templates.fileHeader: Specifies the file header comment for new Java file. Supports configuring multi-line comments with an array of strings, and using ${variable} to reference the predefined variables. java.templates.typeComment: Specifies the type comment for new Java type. Supports configuring multi-line comments with an array of strings, and using ${variable} to reference the predefined variables. java.references.includeAccessors: Include getter, setter and builder/constructor when finding references. Default to true. java.configuration.maven.globalSettings : Path to Maven's global settings.xml. java.configuration.maven.lifecycleMappings : Path to Maven's lifecycle mappings xml. java.eclipse.downloadSources : Enable/disable download of Maven source artifacts for Eclipse projects. java.references.includeDecompiledSources : Include the decompiled sources when finding references. Default to true. java.project.sourcePaths: Relative paths to the workspace where stores the source files. Only effective in the WORKSPACE scope. The setting will NOT affect Maven or Gradle project. java.typeHierarchy.lazyLoad: Enable/disable lazy loading the content in type hierarchy. Lazy loading could save a lot of loading time but every type should be expanded manually to load its content. java.codeGeneration.insertionLocation: Specifies the insertion location of the code generated by source actions. Defaults to afterCursor. afterCursor: Insert the generated code after the member where the cursor is located. beforeCursor: Insert the generated code before the member where the cursor is located. lastMember: Insert the generated code as the last member of the target type. java.codeGeneration.addFinalForNewDeclaration: Whether to generate the 'final' modifer for code actions that create new declarations. Defaults to none. none: Do not generate final modifier fields: Generate 'final' modifier only for new field declarations variables: Generate 'final' modifier only for new variable declarations all: Generate 'final' modifier for all new declarations java.settings.url : Specifies the url or file path to the workspace Java settings. See Setting Global Preferences java.symbols.includeSourceMethodDeclarations : Include method declarations from source files in symbol search. Defaults to false. java.quickfix.showAt : Show quickfixes at the problem or line level. java.configuration.workspaceCacheLimit : The number of days (if enabled) to keep unused workspace cache data. Beyond this limit, cached workspace data may be removed. java.import.generatesMetadataFilesAtProjectRoot : Specify whether the project metadata files(.project, .classpath, .factorypath, .settings/) will be generated at the project root. Defaults to false. java.inlayHints.parameterNames.enabled: Enable/disable inlay hints for parameter names. Supported values are: none(disable parameter name hints), literals(Enable parameter name hints only for literal arguments) and all(Enable parameter name hints for literal and non-literal arguments). Defaults to literals. java.compile.nullAnalysis.nonnull: Specify the Nonnull annotation types to be used for null analysis. If more than one annotation is specified, then the topmost annotation will be used first if it exists in your project dependencies. This setting will be ignored if java.compile.nullAnalysis.mode is set to disabled. java.compile.nullAnalysis.nullable: Specify the Nullable annotation types to be used for null analysis. If more than one annotation is specified, then the topmost annotation will be used first if it exists in your project dependencies. This setting will be ignored if java.compile.nullAnalysis.mode is set to disabled. java.compile.nullAnalysis.nonnullbydefault: Specify the NonNullByDefault annotation types to be used for null analysis. If more than one annotation is specified, then the topmost annotation will be used first if it exists in your project dependencies. This setting will be ignored if java.compile.nullAnalysis.mode is set to disabled. java.import.maven.offline.enabled: Enable/disable the Maven offline mode. Defaults to false. java.codeAction.sortMembers.avoidVolatileChanges: Reordering of fields, enum constants, and initializers can result in semantic and runtime changes due to different initialization and persistence order. This setting prevents this from occurring. Defaults to true. java.jdt.ls.protobufSupport.enabled: Specify whether to automatically add Protobuf output source directories to the classpath. Note: Only works for Gradle com.google.protobuf plugin 0.8.4 or higher. Defaults to true. java.jdt.ls.androidSupport.enabled: [Experimental] Specify whether to enable Android project importing. When set to auto, the Android support will be enabled in Visual Studio Code - Insiders. Note: Only works for Android Gradle Plugin 3.2.0 or higher. Defaults to auto. java.completion.postfix.enabled: Enable/disable postfix completion support. Defaults to true. java.completion.chain.enabled: Enable/disable chain completion support. Defaults to false. java.completion.matchCase: Specify whether to match case for code completion. Defaults to firstLetter. java.compile.nullAnalysis.mode: Specify how to enable the annotation-based null analysis. Supported values are disabled (disable the null analysis), interactive (asks when null annotation types are detected), automatic (automatically enable null analysis when null annotation types are detected). Defaults to interactive. java.cleanup.actionsOnSave: Deprecated, please use 'java.cleanup.actions' instead. The list of clean ups to be run on the current document when it's saved. Clean ups can automatically fix code style or programming mistakes. Click here to learn more about what each clean up does. java.cleanup.actions: The list of clean ups to be run on the current document when it's saved or when the cleanup command is issued. Clean ups can automatically fix code style or programming mistakes. Click here to learn more about what each clean up does. java.saveActions.cleanup: Enable/disable cleanup actions on save. java.import.gradle.annotationProcessing.enabled: Enable/disable the annotation processing on Gradle projects and delegate to JDT APT. Only works for Gradle 5.2 or higher. java.sharedIndexes.enabled: [Experimental] Specify whether to share indexes between different workspaces. Defaults to auto and the shared indexes is automatically enabled in Visual Studio Code - Insiders. auto on off java.sharedIndexes.location: Specifies a common index location for all workspaces. See default values as follows: Windows: First use "$APPDATA\\.jdt\\index", or "~\\.jdt\\index" if it does not exist macOS: "~/Library/Caches/.jdt/index" Linux: First use "$XDG_CACHE_HOME/.jdt/index", or "~/.cache/.jdt/index" if it does not exist java.refactoring.extract.interface.replace: Specify whether to replace all the occurrences of the subtype with the new extracted interface. Defaults to true. java.import.maven.disableTestClasspathFlag : Enable/disable test classpath segregation. When enabled, this permits the usage of test resources within a Maven project as dependencies within the compile scope of other projects. Defaults to false. java.configuration.maven.defaultMojoExecutionAction : Specifies default mojo execution action when no associated metadata can be detected. Defaults to ignore. java.completion.lazyResolveTextEdit.enabled: [Experimental] Enable/disable lazily resolving text edits for code completion. Defaults to true. java.edit.validateAllOpenBuffersOnChanges: Specifies whether to recheck all open Java files for diagnostics when editing a Java file. Defaults to false. java.editor.reloadChangedSources: Specifies whether to reload the sources of the open class files when their source jar files are changed. Defaults to ask. ask: Ask to reload the sources of the open class files auto: Automatically reload the sources of the open class files manual: Manually reload the sources of the open class files java.edit.smartSemicolonDetection.enabled: Defines the smart semicolon detection. Defaults to false. java.configuration.detectJdksAtStart: Automatically detect JDKs installed on local machine at startup. If you have specified the same JDK version in java.configuration.runtimes, the extension will use that version first. Defaults to true. java.completion.collapseCompletionItems: Enable/disable the collapse of overloaded methods in completion items. Overrides java.completion.guessMethodArguments. Defaults to false. java.diagnostic.filter: Specifies a list of file patterns for which matching documents should not have their diagnostics reported (eg. '**/Foo.java'). java.search.scope: Specifies the scope which must be used for search operation like Find Reference Call Hierarchy Workspace Symbols java.jdt.ls.javac.enabled: [Experimental] Specify whether to enable Javac-based compilation in the language server. Requires running this extension with Java 24. Defaults to off. java.completion.engine: [Experimental] Select code completion engine. Defaults to ecj. java.references.includeDeclarations: Include declarations when finding references. Defaults to true java.jdt.ls.appcds.enabled : [Experimental] Enable Java AppCDS (Application Class Data Sharing) for improvements to extension activation. When set to auto, AppCDS will be enabled in Visual Studio Code - Insiders, and for pre-release versions. Semantic Highlighting Semantic Highlighting fixes numerous syntax highlighting issues with the default Java Textmate grammar. However, you might experience a few minor issues, particularly a delay when it kicks in, as it needs to be computed by the Java Language server, when opening a new file or when typing. Semantic highlighting can be disabled for all languages using the editor.semanticHighlighting.enabled setting, or for Java only using language-specific editor settings. Troubleshooting Check the status of the language tools on the lower right corner (marked with A on image below). It should show ready (thumbs up) as on the image below. You can click on the status and open the language tool logs for further information in case of a failure. status indicator Read the troubleshooting guide for collecting informations about issues you might encounter. Report any problems you face to the project. Contributing This is an open source project open to anyone. Contributions are extremely welcome! For information on getting started, refer to the CONTRIBUTING instructions. Continuous Integration builds can be installed from http://download.jboss.org/jbosstools/jdt.ls/staging/. Download the most recent java-<version>.vsix file and install it by following the instructions here. Stable releases are archived under http://download.jboss.org/jbosstools/static/jdt.ls/stable/. Also, you can contribute your own VS Code extension to enhance the existing features by following the instructions here. Feedback Have a question? Start a discussion on GitHub Discussions, File a bug in GitHub Issues, Chat with us on Gitter, Tweet us with other feedback. License EPL 2.0, See LICENSE for more information.
09-21
build.gradle:plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0.36,6.2)' } version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21. java.toolchain.languageVersion = JavaLanguageVersion.of(21) println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { // The mappings can be changed at any time and must be in the following format. // Channel: Version: // official MCVersion Official field/method names from Mojang mapping files // parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official // // Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge // Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started // // Simply re-run your setup task after changing the mappings to update your workspace. mappings channel: mapping_channel, version: mapping_version // Forge 1.20.6 and newer use official mappings at runtime, so we shouldn't reobf from official to SRG reobf = false // When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game. // In most cases, it is not necessary to enable. // enableEclipsePrepareRuns = true // enableIdeaPrepareRuns = true // This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. // It is REQUIRED to be set to true for this template to function. // See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html copyIdeResources = true // When true, this property will add the folder name of all declared run configurations to generated IDE run configurations. // The folder name can be set on a run configuration using the "folderName" property. // By default, the folder name of a run configuration is the name of the Gradle project containing it. // generateRunFolders = true // This property enables access transformers for use in development, applied to the Minecraft artifact. // The access transformer file can be anywhere in the project. // However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge. // This default location is a best practice to automatically put the file in the right place in the final jar. // See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information. // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Default run configurations. // These can be tweaked, removed, or duplicated as needed. runs { // applies to all the run configs below configureEach { workingDirectory project.file('run') // Optional additional logging. The markers can be added/remove as needed, separated by commas. // "SCAN": For mods scan. // "REGISTRIES": For firing of registry events. // "REGISTRYDUMP": For getting the contents of all registries. // property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' // Recommended for development - enables more descriptive errors at the cost of slower startup and registration. property 'eventbus.api.strictRuntimeChecks', 'true' // arg "-mixin.config=${mod_id}.mixins.json" } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } // This run config launches GameTestServer and runs all registered gametests, then exits. // By default, the server will crash when no gametests are provided. // The gametest system is also enabled by default for other run configs under the /test command. gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { // example of overriding the workingDirectory set in configureEach above workingDirectory project.file('run-data') // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } // Include resources generated by data generators. sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { // Put repositories for dependencies here mavenCentral() maven { name = 'Forge' url = 'https://maven.minecraftforge.net' } maven { name = 'Minecraft libraries' url = 'https://libraries.minecraft.net' } exclusiveContent { forRepository { maven { name = 'Sponge' url = 'https://repo.spongepowered.org/repository/maven-public' } } filter { includeGroupAndSubgroups('org.spongepowered') } } // If you have mod jar dependencies in ./libs, you can declare them as a repository like so. // See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver // flatDir { // dir 'libs' // } } dependencies { // Specify the version of Minecraft to use. // Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact. // The "userdev" classifier will be requested and setup by ForgeGradle. // If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"], // then special handling is done to allow a setup of a vanilla dependency without the use of an external repository. minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" // Forge 1.21.6+ uses EventBus 7, which shifts most of its runtime validation to compile-time via an annotation processor // to improve performance in production environments. This line is required to enable said compile-time validation // in your development environment, helping you catch issues early. annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.10' // Example mod dependency with JEI // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime // compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}" // compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}" // runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}" // Example mod dependency using a mod jar from ./libs with a flat dir repository // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar // The group id is ignored when searching -- in this case, it is "blank" // implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") // For more info: // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html } // This block of code expands all declared replace properties in the specified resource targets. // A missing property will result in an error. Properties are expanded using ${} Groovy notation. // When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. // See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html tasks.named('processResources', ProcessResources) { var replaceProperties = [ minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range, forge_version: forge_version, forge_version_range: forge_version_range, loader_version_range: loader_version_range, mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, mod_authors: mod_authors, mod_description: mod_description, ] inputs.properties replaceProperties filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { expand replaceProperties + [project: project] } } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar) { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors ]) // attributes['MixinConfigs'] = "${mod_id}.mixins.json" } } // Example configuration to allow publishing using the maven-publish plugin publishing { publications { register('mavenJava', MavenPublication) { artifact jar } } repositories { maven { url ="file://${project.projectDir}/mcmodsrepo" } } } tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation } // IntelliJ no longer downloads javadocs and sources by default, this tells Gradle to force IntelliJ to do it. idea.module { downloadJavadoc = downloadSources = true } eclipse { // Run everytime eclipse builds the code //autoBuildTasks genEclipseRuns // Run when importing the project synchronizationTasks 'genEclipseRuns' } // Merge the resources and classes into the same directory, because Java expects modules to be in a single directory. // And if we have it in multiple we have to do performance intensive hacks like having the UnionFileSystem // This will eventually be migrated to ForgeGradle so modders don't need to manually do it. But that is later. sourceSets.each { def dir = layout.buildDirectory.dir("sourcesSets/$it.name") it.output.resourcesDir = dir it.java.destinationDirectory = dir }如何修改
08-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值