Native code usage and analysis

本文深入探讨了Java中native关键字的用法及其与C/C++的联合开发,介绍了native方法的实现步骤,包括编写带有native声明的方法、编译、生成头文件、编写本地方法、生成动态链接库以及运行程序。此外,文章还详细阐述了JNI(Java Native Interface)的使用,解释了如何在Java与本地已编译代码间进行交互,以及JNI的书写步骤和注意事项。文中还讨论了Java中native关键字的作用,适用于哪些情况,并提供了Java本地方法的适用场景。最后,文章展示了如何使用native关键字和JNI实现跨平台功能,同时强调了使用本地方法的优缺点。
 
native关键字用法
native是与C++联合开发的时候用的!java自己开发不用的!

--------------------------------------------------------------------------------
使用native关键字说明这个方法是原生函数,也就是这个方法是用C/C++语言实现的,并且被编译成了DLL,由java去调用。这些函数的 实现体在DLL中,JDK的源代码中并不包含,你应该是看不到的。对于不同的平台它们也是不同的。这也是java的底层机制,实际上java就是在不同的 平台上调用不同的native方法实现对操作系统的访问的。
--------------------------------------------------------------------------------
1。native 是用做java 和其他语言(如c++)进行协作时用的也就是native 后的函数的实现不是用java写的 2。既然都不是java,那就别管它的源代码了,呵呵
--------------------------------------------------------------------------------
native的意思就是通知操作系统,这个函数你必须给我实现,因为我要使用。所以native关键字的函数都是操作系统实现的, java只能调用。
--------------------------------------------------------------------------------
java是跨平台的语言,既然是跨了平台,所付出的代价就是牺牲一些对底层的控制,而java要实现对底层的控制,就需要一些其他语言的帮助,这个就是native的作用了




JNI是Java Native Interface的 缩写。从Java 1.1开始,Java Native Interface (JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计 的,但是它并不妨碍你使用其他语言,只要调用约定受支持就可以了。
使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的,比如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少保证本地代码能工作在任何Java 虚拟机实现下。

JNI(Java Native Interface)的书写步骤

·编写带有native声明的方法的java类
·使用javac命令编译所编写的java类
·使用javah ?jni java类名生成扩展名为h的头文件
·使用C/C++(或者其他编程想语言)实现本地方法
·将C/C++编写的文件生成动态连接库

1) 编写java程序:
这里以HelloWorld为例。
代码1:
class HelloWorld {
public native void displayHelloWorld();

static {
System.loadLibrary("hello");
}

public static void main(String[] args) {
new HelloWorld().displayHelloWorld();
}
}
声明native方法:如果你想将一个方法做为一个本地方法的话,那么你就必须声明改方法为native的,并且不能实现。其中方法的参数和返回值在后面讲述。
Load 动态库:System.loadLibrary("hello");加载动态库(我们可以这样理解:我们的方法displayHelloWorld()没 有实现,但是我们在下面就直接使用了,所以必须在使用之前对它进行初始化)这里一般是以static块进行加载的。同时需要注意的是 System.loadLibrary();的参数“hello”是动态库的名字。
main()方法
2) 编译没有什么好说的了
javac HelloWorld.java
3) 生成扩展名为h的头文件
javah ?jni HelloWorld
头文件的内容:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: displayHelloWorld
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
(这 里我们可以这样理解:这个h文件相当于我们在java里面的接口,这里声明了一个Java_HelloWorld_displayHelloWorld (JNIEnv *, jobject);方法,然后在我们的本地方法里面实现这个方法,也就是说我们在编写C/C++程序的时候所使用的方法名必须和这里的一致)。
4) 编写本地方法
实现和由javah命令生成的头文件里面声明的方法名相同的方法。
代码2:
1 #include
2 #include "HelloWorld.h"
3 #include

4 JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}
注意代码2中的第1行,需要将jni.h(该文件可以在%JAVA_HOME%/include文件夹下面找到)文件引入,因为在程序中的 JNIEnv、jobject等类型都 是在该头文件中定义的;另外在第2行需要将HelloWorld.h头文件引入(我是这么理解的:相当于我们在编写java程序的时候,实现一个接口的话 需要声明才可以,这里就是将HelloWorld.h头文件里面声明的方法加以实现。当然不一定是这样)。然后保存为HelloWorldImpl.c就 ok了。
5) 生成动态库
这里以在Windows中为例,需要生成dll文件。在保存HelloWorldImpl.c文件夹下面,使用VC的编译器cl成。
cl -I%java_home%\include -I%java_home%\include\win32 -LD HelloWorldImp.c -Fehello.dll
注 意:生成的dll文件名在选项-Fe后面配置,这里是hello,因为在HelloWorld.java文件中我们loadLibary的时候使用的名字 是hello。当然这里修改之后那里也需要修改。另外需要将-I%java_home%\include -I%java_home%\include\win32参数加上,因为在第四步里面编写本地方法的时候引入了jni.h文件。
6) 运行程序
java HelloWorld就ok。



JNI(Java Native Interface)调用中考虑的问题

在首次使用JNI的时候有些疑问,后来在使用中一一解决,下面就是这些问题的备忘:

1。 java和c是如何互通的?
其实不能互通的原因主要是数据类型的问题,jni解决了这个问题,例如那个c文件中的jstring数据类型就是java传入的String对象,经过jni函数的转化就能成为c的char*。
对应数据类型关系如下表:
Java 类型 本地c类型 说明
boolean jboolean 无符号,8 位
byte jbyte 无符号,8 位
char jchar 无符号,16 位
short jshort 有符号,16 位
int jint 有符号,32 位
long jlong 有符号,64 位
float jfloat 32 位
double jdouble 64 位
void void N/A

2. 如何将java传入的String参数转换为c的char*,然后使用?
java 传入的String参数,在c文件中被jni转换为jstring的数据类型,在c文件中声明char* test,然后test = (char*)(*env)->GetStringUTFChars(env, jstring, NULL);注意:test使用完后,通知虚拟机平台相关代码无需再访问:(*env)->ReleaseStringUTFChars(env, jstring, test);

3. 将c中获取的一个char*的buffer传递给java?
这个char*如果是一般的字符串的话,作为string传回去就可以了。如果是含有’\0’的buffer,最好作为bytearray传出,因为可以制定copy的length,如果copy到string,可能到’\0’就截断了。
有两种方式传递得到的数据:
一种是在jni中直接new一个byte数组,然后调用函数(*env)->SetByteArrayRegion(env, bytearray, 0, len, buffer);将buffer的值copy到bytearray中,函数直接return bytearray就可以了。
一种是return错误号,数据作为参数传出,但是java的基本数据类型是传值,对象是传递的引用,所以将这个需要传出的byte数组用某个类包一下,如下:
class RetObj
{
public byte[] bytearray;
}
这个对象作为函数的参数retobj传出,通过如下函数将retobj中的byte数组赋值便于传出。代码如下:
jclass cls;
jfieldID fid;
jbyteArray bytearray;
bytearray = (*env)->NewByteArray(env,len);
(*env)->SetByteArrayRegion(env, bytearray, 0, len, buffer);
cls = (*env)->GetObjectClass(env, retobj);
fid = (*env)->GetFieldID(env, cls, "retbytes", "[B"]);
(*env)->SetObjectField(env, retobj, fid, bytearray);

4. 不知道占用多少空间的buffer,如何传递出去呢?
在jni的c文件中new出空间,传递出去。java的数据不初始化,指向传递出去的空间即可。









Java中Native关键字的作用 
Java不是完美的,Java的不足除了体现在运行速度上要比传统的C++慢许多之外,Java无法直接访问到操作系统底层(如系统硬件等),为此Java使用native方法来扩展Java程序的功能。
可以将native方法比作Java程序同C程序的接口,其实现步骤:
1、在Java中声明native()方法,然后编译;
2、用javah产生一个.h文件;
3、写一个.cpp文件实现native导出方法,其中需要包含第二步产生的.h文件(注意其中又包含了JDK带的jni.h文件);
4、将第三步的.cpp文件编译成动态链接库文件;
5、在Java中用System.loadLibrary()方法加载第四步产生的动态链接库文件,这个native()方法就可以在Java中被访问了。


JAVA本地方法适用的情况
1.为了使用底层的主机平台的某个特性,而这个特性不能通过JAVA API访问

2.为了访问一个老的系统或者使用一个已有的库,而这个系统或这个库不是用JAVA编写的

3.为了加快程序的性能,而将一段时间敏感的代码作为本地方法实现。


首先写好JAVA文件
/*
* Created on 2005-12-19 Author shaoqi
*/
package com.hode.hodeframework.modelupdate;

public class CheckFile
{
public native void displayHelloWorld();

static
{
System.loadLibrary("test");
}

public static void main(String[] args) {
new CheckFile().displayHelloWorld();
}
}
然后根据写好的文件编译成CLASS文件
然后在classes或bin之类的class根目录下执行javah -jni com.hode.hodeframework.modelupdate.CheckFile,
就会在根目录下得到一个com_hode_hodeframework_modelupdate_CheckFile.h的文件
然后根据头文件的内容编写com_hode_hodeframework_modelupdate_CheckFile.c文件
#include "CheckFile.h"
#include
#include

JNIEXPORT void JNICALL Java_com_hode_hodeframework_modelupdate_CheckFile_displayHelloWorld(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}
之后编译生成DLL文件如“test.dll”,名称与System.loadLibrary("test")中的名称一致
vc的编译方法:cl -I%java_home%\include -I%java_home%\include\win32 -LD com_hode_hodeframework_modelupdate_CheckFile.c -Fetest.dll
最后在运行时加参数-Djava.library.path=[dll存放的路径]




一. 什么是Native Method
简单地讲,一个Native Method就是一个java调用非java代码的接口。一个Native Method是这样一个java的方法:该方法的实现由非java语言实现,比如C。这个特征并非java所特有,很多其它的编程语言都有这一机制,比如 在C++中,你可以用extern "C"告知C++编译器去调用一个C的函数。
"A native method is a Java method whose implementation is provided by non-java code."
在定义一个native method时,并不提供实现体(有些像定义一个java interface),因为其实现体是由非java语言在外面实现的。,下面给了一个示例:   
public class IHaveNatives
{
native public void Native1( int x ) ;
native static public long Native2() ;
native synchronized private float Native3( Object o ) ;
native void Native4( int[] ary ) throws Exception ;
}
这些方法的声明描述了一些非java代码在这些java代码里看起来像什么样子(view).
标识符native可以与所有其它的java标识符连用,但是abstract除外。这是合理的,因为native暗示这些方法是有实现体的,只不过这些 实现体是非java的,但是abstract却显然的指明这些方法无实现体。native与其它java标识符连用时,其意义同非Native Method并无差别,比如native static表明这个方法可以在不产生类的实例时直接调用,这非常方便,比如当你想用一个native method去调用一个C的类库时。上面的第三个方法用到了native synchronized,JVM在进入这个方法的实现体之前会执行同步锁机制(就像java的多线程。)
一个native method方法可以返回任何java类型,包括非基本类型,而且同样可以进行异常控制。这些方法的实现体可以制一个异常并且将其抛出,这一点与java 的方法非常相似。当一个native method接收到一些非基本类型时如Object或一个整型数组时,这个方法可以访问这非些基本型的内部,但是这将使这个native方法依赖于你所访 问的java类的实现。有一点要牢牢记住:我们可以在一个native method的本地实现中访问所有的java特性,但是这要依赖于你所访问的java特性的实现,而且这样做远远不如在java语言中使用那些特性方便和 容易。
native method的存在并不会对其他类调用这些本地方法产生任何影响,实际上调用这些方法的其他类甚至不知道它所调用的是一个本地方法。JVM将控制调用本地 方法的所有细节。需要注意当我们将一个本地方法声明为final的情况。用java实现的方法体在被编译时可能会因为内联而产生效率上的提升。但是一个 native final方法是否也能获得这样的好处却是值得怀疑的,但是这只是一个代码优化方面的问题,对功能实现没有影响。
如果一个含有本地方法的类被继承,子类会继承这个本地方法并且可以用java语言重写这个方法(这个似乎看起来有些奇怪),同样的如果一个本地方法被fianl标识,它被继承后不能被重写。
本地方法非常有用,因为它有效地扩充了jvm.事实上,我们所写的java代码已经用到了本地方法,在sun的java的并发(多线程)的机制实现中,许 多与操作系统的接触点都用到了本地方法,这使得java程序能够超越java运行时的界限。有了本地方法,java程序可以做任何应用层次的任务。


二.为什么要使用Native Method
java使用起来非常方便,然而有些层次的任务用java实现起来不容易,或者我们对程序的效率很在意时,问题就来了。
与java环境外交互:
有时java应用需要与java外面的环境交互。这是本地方法存在的主要原因,你可以想想java需要与一些底层系统如操作系统或某些硬件交换信息时的情 况。本地方法正是这样一种交流机制:它为我们提供了一个非常简洁的接口,而且我们无需去了解java应用之外的繁琐的细节。
与操作系统交互:
JVM支持着java语言本身和运行时库,它是java程序赖以生存的平台,它由一个解释器(解释字节码)和一些连接到本地代码的库组成。然而不管怎 样,它毕竟不是一个完整的系统,它经常依赖于一些底层(underneath在下面的)系统的支持。这些底层系统常常是强大的操作系统。通过使用本地方 法,我们得以用java实现了jre的与底层系统的交互,甚至JVM的一些部分就是用C写的,还有,如果我们要使用一些java语言本身没有提供封装的操 作系统的特性时,我们也需要使用本地方法。
Sun's Java
Sun的解释器是用C实现的,这使得它能像一些普通的C一样与外部交互。jre大部分是用java实现的,它也通过一些本地方法与外界交互。例如:类 java.lang.Thread 的 setPriority()方法是用java实现的,但是它实现调用的是该类里的本地方法setPriority0()。这个本地方法是用C实现的,并被 植入JVM内部,在Windows 95的平台上,这个本地方法最终将调用Win32 SetPriority() API。这是一个本地方法的具体实现由JVM直接提供,更多的情况是本地方法由外部的动态链接库(external dynamic link library)提供,然后被JVM调用。


三.JVM怎样使Native Method跑起来:
我们知道,当一个类第一次被使用到时,这个类的字节码会被加载到内存,并且只会回载一次。在这个被加载的字节码的入口维持着一个该类所有方法描述符的 list,这些方法描述符包含这样一些信息:方法代码存于何处,它有哪些参数,方法的描述符(public之类)等等。
如果一个方法描述符内有native,这个描述符块将有一个指向该方法的实现的指针。这些实现在一些DLL文件内,但是它们会被操作系统加载到java程 序的地址空间。当一个带有本地方法的类被加载时,其相关的DLL并未被加载,因此指向方法实现的指针并不会被设置。当本地方法被调用之前,这些DLL才会 被加载,这是通过调用java.system.loadLibrary()实现的。

最后需要提示的是,使用本地方法是有开销的,它丧失了java的很多好处。如果别无选择,我们可以选择使用本地方法
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值