Compile java class linux

How To Compile and Run Java Program in Linux

Today I’ll explain how to compile and run Java code on Linux environment.

Personally, I like Ubuntu, that’s why I’ll show you how to do it there.

First of all, you have to be sure that Java is installed on your machine.

Correct output is:

If it’s not installed you can do it easy:

Now change directory to your project source folder.

Inside of my project I have a class Car, that I wrote when I talked about the transient keyword in Java.

It looks like this:

How to Compile Java Program

To compile this class I call Linux Java compiler:

If everything was OK you should find a new file Car.class near Car.java.

Our class is compiled, the next step is to run compiled Java class on Ubuntu.

How to Run Java Program

In the previous section, I compiled Java code in Linux.

Now I’m going to show how to run Java program.

Just point Java to compiled class like this:

Note that you should run Java class from the source folder.

For example, if I change directory to project (one level upper than src folder).

and try to run the same class:

So you have to be sure that you’re running your Java code on Ubuntu from the source folder.

For compiling process it doesn’t matter.

As you can see it’s easy to compile and run Java on Linux.

Personally, I prefer Java programming on Linux instead of Windows.

I think Java developers should know at least basic Linux commands.

Источник

Работа с Java в командной строке

От простого к .

Каждая программа обычно содержится в отдельном каталоге. Я придерживаюсь правила создавать в этом каталоге по крайней мере две папки: src и bin. В первой содержатся исходные коды, во второй — результат компиляции. В данных папках будет структура каталогов, зависящая от пакетов.

Один файл

Можно сделать и без лишних папок.
Берем сам файл HelloWorld.java.
Переходим в каталог, где лежит данный файл, и выполняем команды.
В данной папке появится файл HelloWorld.class. Значит программа скомпилирована. Чтобы запустить

Отделяем бинарные файлы от исходников

Теперь сделаем тоже самое, но с каталогами. Создадим каталог HelloWorld и в нем две папки src и bin.
Компилируем
Здесь мы указали, что бинарные файлы будут сохраняться в отдельную папку bin и не путаться с исходниками.

Используем пакеты

А то, вдруг, программа перестанет быть просто HelloWorld-ом. Пакетам лучше давать понятное и уникальное имя. Это позволит добавить данную программу в другой проект без конфликта имен. Прочитав некоторые статьи, можно подумать, что для имени пакета обязательно нужен домен. Это не так. Домены — это удобный способ добиться уникальности. Если своего домена нет, воспользуйтесь аккаунтом на сайте (например, ru.habrahabr.mylogin). Он будет уникальным. Учтите, что имена пакетов должны быть в нижнем регистре. И избегайте использования спецсимволов. Проблемы возникают из-за разных платформ и файловых систем.

Поместим наш класс в пакет с именем com.qwertovsky.helloworld. Для этого добавим в начало файла строчку
В каталоге src создадим дополнительные каталоги, чтобы путь к файлу выглядел так: src/com/qwertovsky/helloworld/HelloWorld.java.
Компилируем
В каталоге bin автоматически создастся структура каталогов как и в src.

Если в программе несколько файлов

HelloWorld.java
Calculator.java
Adder.java

Ошибка возникла из-за того, что для компиляции нужны файлы с исходными кодами классов, которые используются (класс Calculator). Надо указать компилятору каталог с файлами с помощью ключа -sourcepath.
Компилируем

Если удивляет результат

Есть возможность запустить отладчик. Для этого существует jdb.
Сначала компилируем с ключом -g, чтобы у отладчика была информация.

Отладчик запускает свой внутренний терминал для ввода команд. Справку по последним можно вывести с помощью команды help.
Указываем точку прерывания на 9 строке в классе Calculator

Запускаем на выполнение.

Чтобы соориентироваться можно вывести кусок исходного кода, где в данный момент находится курссор.

Узнаем, что из себя представляет переменная а.

Выполним код в текущей строке и увидим, что sum стала равняться 2.

Поднимемся из класса Adder в вызвавший его класс Calculator.

Удаляем точку прерывания

Можно избежать захода в методы, используя команду next.

Проверяем значение выражения и завершаем выполнение.

Хорошо бы протестировать

Запускаем. В качестве разделителя нескольких путей в classpath в Windows используется ‘;’, в Linux — ‘:’. В консоли Cygwin не работают оба разделителя. Возможно, должен работать ‘;’, но он воспринимается как разделитель команд.

Создадим библиотеку

Класс Calculator оказался полезным и может быть использован во многих проектах. Перенесем всё, что касается класса Calculator в отдельный проект.

Измените также назавания пакетов в исходных текстах. В HelloWorld.java нужно будет добавить строку

Делаем архив jar

С помощью ключа -C мы запустили программу в каталоге bin.

Надо узнать, что у библиотеки внутри

Можно распаковать архив zip-распаковщиком и посмотреть, какие классы есть в библиотеке.
Информацию о любом классе можно получить с помощью дизассемблера javap.

Из результата видно, что класс содержит кроме пустого конструктора, ещё один метод sum, внутри которого в цикле вызывается метод add класса Adder. По завершении метода sum, вызывается Adder.getSum().
Без ключа -c программа выдаст только список переменных и методов (если использовать -private, то всех).

Лучше снабдить библиотеку документацией

Изменим для этого класс калькулятора.

Документацию можно создать следующей командой. При ошибке программа выдаст список возможных опций.

В результате получиться следующее

Можно подписать jar-архив

Если требуется подписать свою библиотеку цифровой подписью, на помощь придут keytool и jarsigner.
Генерируем подпись.

Генерируем Certificate Signing Request (CSR)

Содержимое полученного файла отправляем в центр сертификации. От центра сертификации получаем сертификат. Сохраняем его в файле (например, qwertokey.cer) и импортируем в хранилище

Файл qwertokey.cer отправляем всем, кто хочет проверить архив. Проверяется он так

Использование библиотеки

Есть программа HelloWorld, которая использует библиотечный класс Calculator. Чтобы скомпилировать и запустить программу, нужно присоединить библиотеку.
Компилируем

Собираем программу

Это можно сделать по-разному.

Первый способ

Здесь есть тонкости.
В строке

не должно быть пробелов в конце.
Вторая тонкость описана в [3]: в этой же строке должен стоять перенос на следующую строку. Это если манифест помещается в архив сторонним архиватором.
Программа jar не включит в манифест последнюю строку из манифеста, если в конце не стоит перенос строки.
Ещё момент: в манифесте не должно быть пустых строк между строками. Будет выдана ошибка «java.io.IOException: invalid manifest format».

При использовании команды echo надо следить только за пробелом в конце строки с main-class.

Второй способ

В данном способе избегаем ошибки с пробелом в main-class.

Третий способ

Включили код нужной библиотеки в исполняемый файл.

Запуск исполняемого jar-файла

Файл calculator.jar исполняемым не является. А вот helloworld.jar можно запустить.
Если архив был создан первыми двумя способами, то рядом с ним в одном каталоге должна находится папка lib с файлом calculator.jar. Такие ограничения из-за того, что в манифесте в class-path указан путь относительно исполняемого файла.

При использовании третьего способа нужные библиотеки включаются в исполняемый файл. Держать рядом нужные библиотеки не требуется. Запускается аналогично.

Как быть с приложениями JavaEE

Аналогично. Только библиотеки для компиляции нужно брать у сервера приложений, который используется. Если я использую JBoss, то для компиляции сервлета мне нужно будет выполнить примерно следующее

Структура архива JavaEE-приложения должна соответствовать определенному формату. Например

Способы запуска приложения на самом сервере с помощью командной строки для каждого сервера различны.

Надеюсь, данная статья станет для кого-нибудь шпаргалкой для работы с Java в командной строке. Данные навыки помогут понять содержание и смысл Ant-скриптов и ответить на собеседовании на более каверзные вопросы, чем «Какая IDE Вам больше нравится?».

Источник

Как скомпилировать файл .java на Ubuntu?

Как я могу скомпилировать файл .java?

Какие программы мне понадобятся? Если мне нужен Java JDK, мне также понадобится помощь в установке этого. Я очень новичок в Ubuntu, поэтому любая программа, которую мне нужно установить, мне понадобится учебник по установке.

4 ответа

OpenJDK работает лучше всего для меня. Это просто, и я никогда с ним не сталкивался. Просто выполните следующие простые шаги:

From Terminal install open jdk Напишите программу java и сохраните файл как filename.java Теперь для компиляции используйте эту команду с терминала . Если все работает хорошо, тогда необходимо создать новый файл «filename.class». Для запуска вашей программы, которую вы только что скомпилировали, введите следующую команду в терминале:

Вы можете использовать любой текстовый редактор (например, gedit),

замените имя файла на любое имя, которое вы хотите

, вам нужно быть в том же каталоге, что и «настоящий рабочий каталог» (полученный при запуске pwd) во время выполнения команды с терминала. [!d14 ]

Если, например, ваш файл my_file.java:

Вы хотите сделать:

Тем не менее, это общепринятое соглашение, дающее классы и файлы с тем же именем.

Вам необходимо установить JDK, Java Development Kit. Ubuntu содержит metapackage default-jdk, который зависит от выбранного в настоящее время JDK. Теперь это openjdk-6-jdk.

Чтобы скомпилировать файл Java в исполняемый файл .class, вы можете запустить

и запустить его

Это самый простой случай использования, и в основном он не работает, потому что классы java в основном зависят от других классов Java, размещенных в библиотеках.

Таким образом, вы, вероятно, хотели бы использовать более сложные решения. Большинство текстовых редакторов поддерживают подсветку синтаксиса Java, например default-jdk , kate или vim, но они не решают проблему с компиляцией.

У вас есть другой вариант — вы можете установить полнофункциональная Java IDE. Ubuntu поставляется с главными Java IDE OpenSource — kate и Eclipse.

Просто введите sudo apt-get update, а затем sudo apt-get install openjdk-7-jdk для быстрой установки для java7, затем вы можете играть в игры с помощью java: -)

Для получения более подробной официальной документации по Java, перейдите по этой ссылке.

Источник

javac

You can use the javac tool and its options to read Java class and interface definitions and compile them into bytecode and class files.

One or more source files to be compiled (such as MyClass.java ) or processed for annotations (such as MyPackage.MyClass ).

The javac command reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. The javac command can also process annotations in Java source files and classes.

In JDK 9, a new launcher environment variable, JDK_JAVAC_OPTIONS , has been introduced that prepends its content to the command line to javac . See Using JDK_JAVAC_OPTIONS Environment Variable.

There are two ways to pass source code file names to javac .

For a small number of source files, you can list the file names on the command line.

For a large number of source files, you can use the @ filename option on the javac command line to include a file that lists the source file names. See Standard Options for javac for a description of the option and javac Command-Line Argument Files for a description of javac argument files.

Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class .

Читайте также:  Оператор для windows mobile

Inner class definitions produce additional class files. These class files have names that combine the inner and outer class names, such as MyClass$MyInnerClass.class .

You should arrange the source files in a directory tree that reflects their package tree. For example:

Oracle Solaris, Linux, and OS X : If all of your source files are in /workspace , then put the source code for com.mysoft.mypack.MyClass in /workspace/com/mysoft/mypack/MyClass.java .

Windows: If all of your source files are in \workspace , then put the source code for com.mysoft.mypack.MyClass in \workspace\com\mysoft\mypack\MyClass.java .

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d option described in Standard Options for javac.

The javac command supports the new Java Compiler API defined by the classes and interfaces in the javax.tools package.

Implicitly Loaded Source Files

To compile a set of source files, the compiler might need to implicitly load additional source files. See Searching for Types. Such files are currently not subject to annotation processing. By default, the compiler gives a warning when annotation processing occurs and any implicitly loaded source files are compiled. The -implicit option provides a way to suppress the warning.

Using JDK_JAVAC_OPTIONS Environment Variable

The content of the JDK_JAVAC_OPTIONS environment variable, separated by white-spaces ( ) or white-space characters ( \n , \t , \r , or \f ) is prepended to the command line arguments passed to javac as a list of arguments.

The encoding requirement for the environment variable is the same as the javac command line on the system. JDK_JAVAC_OPTIONS environment variable content is treated in the same manner as that specified in the command line.

Single ( ‘ ) or double ( » ) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes. In case a matching quote is not found, the launcher will abort with an error message. @ files are supported as they are specified in the command line. However, as in @ files , use of a wildcard is not supported.

Examples of quoting arguments containing white spaces:

Overview of javac Options

The compiler has sets of standard options, and cross-compilation options that are supported on the current development environment. The compiler also has a set of nonstandard options that are specific to the current virtual machine and compiler implementations but are subject to change in the future. The nonstandard options begin with -X . The different sets of javac options are described in the following sections:

Standard Options for javac

Reads options and file names from a file. To shorten or simplify the javac command, you can specify one or more files that contain arguments to the javac command (except -J options). This let’s you to create javac commands of any length on any operating system. See javac Command-Line Argument Files.

Specifies options to pass to annotation processors. These options aren’t interpreted by javac directly, but are made available for use by individual processors. The key value should be one or more identifiers separated by a dot (.).

—add-modules module , module

Specifies root modules to resolve in addition to the initial modules, or all modules on the module path if module is ALL-MODULE-PATH.

—boot-class-path path or -bootclasspath path

Overrides the location of the bootstrap class files.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Specifies where to find user class files and annotation processors. This class path overrides the user class path in the CLASSPATH environment variable.

If —class-path , -classpath , or -cp aren’t specified, then the user class path is the current directory.

If the -sourcepath option isn’t specified, then the user class path is also searched for source files.

If the -processorpath option isn’t specified, then the class path is also searched for annotation processors.

Sets the destination directory for class files. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed. For example:

Oracle Solaris, Linux, and OS X : If you specify -d /home/myclasses and the class is called com.mypackage.MyClass , then the class file is /home/myclasses/com/mypackage/MyClass.class .

Windows: If you specify -d C:\myclasses and the class is called com.mypackage.MyClass , then the class file is C:\myclasses\com\mypackage\MyClass.class .

If the -d option isn’t specified, then javac puts each class file in the same directory as the source file from which it was generated.

The directory specified by the -d option isn’t automatically added to your user class path.

Shows a description of each use or override of a deprecated member or class. Without the -deprecation option, javac shows a summary of the source files that use or override deprecated members or classes. The -deprecation option is shorthand for -Xlint:deprecation .

Specifies character encoding used by source files, such as EUC-JP and UTF-8. If the -encoding option isn’t specified, then the platform default converter is used.

Overrides the location of the endorsed standards path.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Overrides the location of the installed extensions. The directories variable is a colon-separated list of directories. Each JAR file in the specified directories is searched for class files. All JAR files found become part of the class path.

If you are cross-compiling, then this option specifies the directories that contain the extension classes. See Cross-Compilation Options for javac.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Generates all debugging information, including local variables. By default, only line number and source file information is generated.

-g:[lines, vars, source],[lines, vars, source],[lines, vars, source]

Generates only the kinds of debugging information specified by the comma-separated list of keywords. Valid keywords are:

Line number debugging information.

Local variable debugging information.

Source file debugging information.

Doesn’t generate any debugging information.

Specifies where to place generated native header files.

When you specify this option, a native header file is generated for each class that contains native methods or that has one or more constants annotated with the java.lang.annotation.Native annotation. If the class is part of a package, then the compiler puts the native header file in a subdirectory that reflects the package name and creates directories as needed.

Prints a synopsis of the standard options.

Prints the help for extra options.

Specifies whether or not to generate class files for implicitly referenced files:

-implicit:class — Automatically generates class files.

-implicit:none — Suppresses class file generation.

If this option isn’t specified, then the default automatically generates class files. In this case, the compiler issues a warning if any class files are generated when also doing annotation processing. The warning isn’t issued when the -implicit option is explicitly set. See Searching for Types.

Passes option to the runtime system, where option is one of the Java options described on javacommand. For example, -J-Xms48m sets the startup memory to 48 MB.

The CLASSPATH environment variable, -classpath option, -bootclasspath option, and -extdirs option don’t specify the classes used to run javac . Trying to customize the compiler implementation with these options and variables is risky and often doesn’t accomplish what you want. If you must customize the complier implementation, then use the -J option to pass options through to the underlying Java launcher.

Limits the universe of observable modules.

—module module-name or -m module-name

Compiles only the specified module and checks time stamps.

—module-path path or -p path

Specifies where to find application modules.

Specifies where to find input source files for multiple modules.

—module-version version Specifies the version of modules that are being compiled. -nowarn

Disables warning messages. This option operates the same as the -Xlint:none option.

Generates metadata for reflection on method parameters. Stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.

-proc: [none, only] , [none, only]

Controls whether annotation processing and compilation are done. -proc:none means that compilation takes place without annotation processing. -proc:only means that only annotation processing is done, without any subsequent compilation.

-processor class1 [, class2 , class3 . ]

Names of the annotation processors to run. This bypasses the default discovery process.

—processor-module—path path or -p module-path

Specifies the module path used for finding annotation processors.

—processor—path path or -processorpath path

Specifies where to find annotation processors. If this option isn’t used, then the class path is searched for processors.

Checks that the API used is available in the specified profile.

Not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Compiles against the public, supported and documented API for a specific VM version. Supported release targets are 6 , 7 , 8 , and 9 .

When using —release for a version of the Java Platform that supports modules, you can’t use —add-modules to access internal JDK modules, nor can you use —add-exports to access internal JDK APIs in the modules.

Specifies the directory used to place the generated source files. If a class is part of a package, then the compiler puts the source file in a subdirectory that reflects the package name and creates directories as needed. For example:

Oracle Solaris, Linux, and OS X : : If you specify -s /home/mysrc and the class is called com.mypackage.MyClass , then the source file is put in /home/mysrc/com/mypackage/MyClass.java .

Windows : If you specify -s C:\mysrc and the class is called com.mypackage.MyClass , then the source file is put in C:\mysrc\com\mypackage\MyClass.java .

Specifies the version of source code accepted. The following values for release are allowed:

As of JDK 9, the javac doesn’t support -source release settings less than or equal to 5 . If settings less than or equal to 5 are used, then the javac command behaves as if -source 6 were specified.

No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors instead of warnings as was done in earlier releases of Java Platform, Standard Edition.

The compiler accepts code with features introduced in Java SE 7.

The compiler accepts code with features introduced in Java SE 8.

The default value. The compiler accepts code with features introduced in Java SE 9.

—source-path path or -sourcepath path

Specifies where to find input source files. This is the source code path used to search for class or interface definitions. As with the user class path, source path entries are separated by colons (:) on Oracle Solaris and semicolons(;) on Windows. They can be directories, JAR archives, or ZIP archives. If packages are used, then the local path name within the directory or archive must reflect the package name.

Classes found through the class path might be recompiled when their source files are also found. See Searching for Types.

Читайте также:  Компьютер не видит локальный диск windows 10

Overrides the location of system modules.

Generates class files for a specific VM version.

Overrides the location of upgradeable modules.

Outputs messages about what the compiler is doing. Messages include information about each class loaded and each source file compiled.

—version or -version

Prints version information.

Terminates compilation when warnings occur.

Cross-Compilation Options for javac

By default, for releases prior to JDK 9, classes were compiled against the bootstrap classes of the platform that shipped with the javac command. But javac also supports cross-compiling, in which classes are compiled against bootstrap classes of a different Java platform implementation. It’s important to use the -bootclasspath and -extdirs options when cross-compiling.

Not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Extra Options for javac

—add-exports module / package = other-module (, other-module ) *

Specifies a package to be considered as exported from its defining module to additional modules or to all unnamed modules when the value of other-module is ALL-UNNAMED .

—add-reads module = other-module (, other-module ) *

Specifies additional modules to be considered as required by a given module.

Overrides the location of the endorsed standards path.

Not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Overrides the location of installed extensions.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Specifies the format for documentation comments.

—patch-module module = file (: file ) *

Overrides or augments a module with classes and resources in JAR files or directories.

Overrides the location of the bootstrap class files.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Adds a suffix to the bootstrap class path.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Adds a prefix to the bootstrap class path.

This option is not supported when using —release release to compile for JDK 9. See the description of —release release for details about compiling for versions other than JDK 9.

Selects a diagnostic mode.

Enables recommended checks for problems in javadoc comments

-Xdoclint:(all|none|[-] group ) [/ access ]

Enables or disables specific groups of checks, where group is one of the following values:

For more information about these groups of checks, see the -Xdoclint option of the javadoc command. The -Xdoclint option is disabled by default in the javac command.

The variable access specifies the minimum visibility level of classes and members that the -Xdoclint option checks. It can have one of the following values (in order of most to least visible:)

The default access level is private .

For example, the following option checks classes and members (with all groups of checks) that have the access level of protected and higher (which includes protected and public):

The following option enables all groups of checks for all access levels, except it won’t check for HTML errors for classes and members that have the access level of package and higher (which includes package, protected and public 🙂

Xdoclint/package:[-] packages (,[-] package ) *

Enables or disables checks in specific packages. Each package is either the qualified name of a package or a package name prefix followed by .* , which expands to all sub-packages of the given package. Each package can be prefixed with — to disable checks for a specified package or packages.

Enables all recommended warnings. In this release, enabling all available warnings is recommended.

Supplies warnings to enable or disable, separated by comma. Precede a key by a hypen (-) to disable the specified warning.

Supported values for key are:

all — Enables all warnings.

auxiliaryclass — Warns about an auxiliary class that’s hidden in a source file, and is used from other files.

cast — Warns about the use of unnecessary casts.

classfile — Warns about the issues related to classfile contents.

deprecation — Warns about the use of deprecated items.

dep-ann — Warns about the items marked as deprecated in javadoc but without the @Deprecated annotation.

divzero — Warns about the division by the constant integer 0.

empty — Warns about an empty statement after if .

exports — Warns about the issues regarding module exports.

fallthrough — Warns about the falling through from one case of a switch statement to the next.

finally — Warns about finally clauses that don’t terminate normally.

module — Warns about the module system-related issues.

opens — Warns about the issues related to module opens.

options — Warns about the issues relating to use of command line options.

overloads — Warns about the issues related to method overloads.

overrides — Warns about the issues related to method overrides.

path — Warns about the invalid path elements on the command l ine.

processing — Warns about the issues related to annotation processing.

rawtypes — Warns about the use of raw types.

removal — Warns about the use of an API that has been marked for removal.

serial — Warns about the serializable classes that don’t provide a serial version ID. Also warns about access to non-public members from a serializable element.

static — Warns about the accessing a static member using an instance.

try — Warns about the issues relating to the use of try blocks ( that is, try-with-resources).

unchecked — Warns about the unchecked operations.

varargs — Warns about the potentially unsafe vararg methods.

none — Disables all warnings.

Sets the maximum number of errors to print.

Sets the maximum number of warnings to print.

-Xpkginfo:[always, legacy, nonempty]

Specifies when and how the javac command generates package-info.class files from package-info.java files using one of the following options:

Generates a package-info.class file for every package-info.java file. This option may be useful if you use a build system such as Ant, which checks that each .java file has a corresponding .class file.

Generates a package-info.class file only if package-info.java contains annotations. This option doesn’t generate a package-info.class file if package-info.java contains only comments.

A package-info.class file might be generated but be empty if all the annotations in the package-info.java file have RetentionPolicy.SOURCE .

Generates a package-info.class file only if package-info.java contains annotations with RetentionPolicy.CLASS or RetentionPolicy.RUNTIME .

-Xplugin: name args

Specifies the name and optional arguments for a plug-in to be run.

-Xprefer:[source or newer]

Specifies which file to read when both a source file and class file are found for an implicitly compiled class using one of the following options. See Searching for Types.

-Xprefer:newer — Reads the newer of the source or class files for a type (default).

-Xprefer:source — Reads the source file. Use -Xprefer:source when you want to be sure that any annotation processors can access annotations declared with a retention policy of SOURCE .

Prints a textual representation of specified types for debugging purposes. This doesn’t perform annotation processing or compilation. The format of the output could change.

Prints information about which annotations a processor is asked to process.

Prints information about initial and subsequent annotation processing rounds.

Sends compiler messages to the named file. By default, compiler messages go to System.err .

javac Command-Line Argument Files

An argument file can include javac options and source file names in any combination. The arguments within a file can be separated by spaces or new line characters. If a file name contains embedded spaces, then put the whole file name in double quotation marks.

File names within an argument file are relative to the current directory, not to the location of the argument file. Wildcards (*) aren’t allowed in these lists (such as for specifying *.java ). Use of the at sign ( @ ) to recursively interpret files isn’t supported. The -J options aren’t supported because they’re passed to the launcher, which doesn’t support argument files.

When executing the javac command, pass in the path and name of each argument file with the at sign (@) leading character. When the javac command encounters an argument beginning with the at sign ( @ ), it expands the contents of that file into the argument list.

Examples of Using javac @filename

Single Argument File

You could use a single argument file named argfile to hold all javac arguments:

This argument file could contain the contents of both files shown in Example 2.

Two Argument Files

You can create two argument files: one for the javac options and the other for the source file names. Note that the following lists have no line-continuation characters.

Create a file named options that contains the following:

Oracle Solaris, Linux, and OS X : :

Create a file named classes that contains the following:

Then, run the javac command as follows:

Argument Files with Paths

The argument files can have paths, but any file names inside the files are relative to the current working directory (not path1 or path2 ):

Examples of Using -Xlint keys

Warns about unnecessary and redundant casts, for example:

Warns about issues related to class file contents.

Warns about the use of deprecated items. For example:

The method java.util.Date.getDay has been deprecated since JDK 1.1.

Warns about items that are documented with the @deprecated Javadoc comment, but don’t have the @Deprecated annotation, for example:

Warns about division by the constant integer 0, for example:

Warns about empty statements after if statements, for example:

Checks the switch blocks for fall-through cases and provides a warning message for any that are found. Fall-through cases are cases in a switch block, other than the last case in the block, whose code doesn’t include a break statement, allowing code execution to fall through from that case to the next case. For example, the code following the case 1 label in this switch block doesn’t end with a break statement:

If the -Xlint:fallthrough option was used when compiling this code, then the compiler emits a warning about possible fall-through into case, with the line number of the case in question.

Warns about finally clauses that can’t be completed normally, for example:

The compiler generates a warning for the finally block in this example. When the int method is called, it returns a value of 0. A finally block executes when the try block exits. In this example, when control is transferred to the catch block, the int method exits. However, the finally block must execute, so it’s executed, even though control was transferred outside the method.

Warns about issues that related to the use of command-line options. See Cross-Compilation Options for javac.

Warns about issues related to method overrides. For example, consider the following two classes:

The compiler generates a warning similar to the following:.

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. In the method ClassWithVarargsMethod.varargsMethod , the compiler translates the varargs formal parameter String. s to the formal parameter String[] s , an array that matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod . Consequently, this example compiles.

Warns about invalid path elements and nonexistent path directories on the command line (with regard to the class path, the source path, and other paths). Such warnings can’t be suppressed with the @SuppressWarnings annotation. For example:

Читайте также:  Log out user windows

Oracle Solaris, Linux, and OS X : : javac -Xlint:path -classpath /nonexistentpath Example.java

Windows : javac -Xlint:path -classpath C:\nonexistentpath Example.java

Warns about issues related to annotation processing. The compiler generates this warning when you have a class that has an annotation, and you use an annotation processor that can’t handle that type of exception. For example, the following is a simple annotation processor:

Source file AnnocProc.java :

Source file AnnosWithoutProcessors.java :

The following commands compile the annotation processor AnnoProc , then run this annotation processor against the source file AnnosWithoutProcessors.java :

When the compiler runs the annotation processor against the source file AnnosWithoutProcessors.java , it generates the following warning:

To resolve this issue, you can rename the annotation defined and used in the class AnnosWithoutProcessors from Anno to NotAnno .

Warns about unchecked operations on raw types. The following statement generates a rawtypes warning:

The following example doesn’t generate a rawtypes warning:

List is a raw type. However, List is an unbounded wildcard parameterized type. Because List is a parameterized interface, always specify its type argument. In this example, the List formal argument is specified with an unbounded wildcard ( ? ) as its formal type parameter, which means that the countElements method can accept any instantiation of the List interface.

Warns about missing serialVersionUID definitions on serializable classes, for example:

The compiler generates the following warning:

If a serializable class doesn’t explicitly declare a field named serialVersionUID , then the serialization runtime environment calculates a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. However, it’s strongly recommended that all serializable classes explicitly declare serialVersionUID values because the default process of computing serialVersionUID values is highly sensitive to class details that can vary depending on compiler implementations. As a result, might cause an unexpected InvalidClassExceptions during deserialization. To guarantee a consistent serialVersionUID value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

Warns about issues relating to the use of statics variables, for example:

The compiler generates the following warning:

To resolve this issue, you can call the static method m1 as follows:

Alternately, you can remove the static keyword from the declaration of the method m1 .

Warns about issues relating to the use of try blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac declared in the try block isn’t used:

Gives more detail for unchecked conversion warnings that are mandated by the Java Language Specification, for example:

During type erasure, the types ArrayList and List become ArrayList and List , respectively.

The ls command has the parameterized type List . When the List referenced by l is assigned to ls , the compiler generates an unchecked warning. At compile time, the compiler and JVM can’t determine whether l refers to a List type. In this case, l doesn’t refer to a List type. As a result, heap pollution occurs.

A heap pollution situation occurs when the List object l , whose static type is List , is assigned to another List object, ls , that has a different static type, List . However, the compiler still allows this assignment. It must allow this assignment to preserve backward compatibility with releases of Java SE that don’t support generics. Because of type erasure, List and List both become List . Consequently, the compiler allows the assignment of the object l , which has a raw type of List , to the object ls .

Warns about unsafe use of variable arguments ( varargs ) methods, in particular, those that contain non-reifiable arguments, for example:

A non-reifiable type is a type whose type information isn’t fully available at runtime.

The compiler generates the following warning for the definition of the method ArrayBuilder.addToList :

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language doesn’t permit the creation of arrays of parameterized types. In the method ArrayBuilder.addToList , the compiler translates the varargs formal parameter T. elements to the formal parameter T[] elements, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements. Consequently, there’s a possibility of heap pollution.

Example of Compiling by Providing Command-Line Arguments

To compile as though providing command-line arguments, use the following syntax:

The example writes diagnostics to the standard output stream and returns the exit code that javac command would give when called from the command line.

You can use other methods in the javax.tools.JavaCompiler interface to handle diagnostics, control where files are read from and written to, and more.

This API is retained for backward compatibility only. All new code should use the Java Compiler API.

The com.sun.tools.javac.Main class provides two static methods to call the compiler from a program:

The args parameter represents any of the command-line arguments that would typically be passed to the compiler.

The out parameter indicates where the compiler diagnostic output is directed.

The return value is equivalent to the exit value from javac .

All other classes and methods found in a package with names that start with com.sun.tools.javac (subpackages of com.sun.tools.javac ) are strictly internal and subject to change at any time.

Example of Compiling Multiple Source Files

This example compiles the Aloha.java , GutenTag.java , Hello.java , and Hi.java source files in the greetings package.

Oracle Solaris, Linux, and OS X : :

Example of Specifying a User Class Path

After changing one of the source files in the previous example, recompile it:

Oracle Solaris, Linux, and OS X : :

Because greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The previous example works because the default user class path is the directory that contains the package directory. If you want to recompile this file without concern for which directory you are in, then add the examples directory to the user class path by setting CLASSPATH . This example uses the -classpath option.

Oracle Solaris, Linux, and OS X : :

If you change greetings.Hi to use a banner utility, then that utility also needs to be accessible through the user class path.

Oracle Solaris, Linux, and OS X : :

To execute a class in the greetings package, the program needs access to the greetings package, and to the classes that the greetings classes use.

Oracle Solaris, Linux, and OS X : :

The -source 1.7 option specifies that release 1.7 (or 7) of the Java programming language must be used to compile OldCode.java. The -target 1.7 option ensures that the generated class files are compatible with JVM 1.7.

Annotation Processing

The javac command provides direct support for annotation processing, superseding the need for the separate annotation processing command, apt .

The API for annotation processors is defined in the javax.annotation.processing and javax.lang.model packages and subpackages.

How Annotation Processing Works

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option. If no path is specified, then the user class path is used. Processors are located by means of service provider-configuration files named META-INF/services/javax.annotation.processing . Processor on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.

After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine what annotations they process. When a match is found, the processor is called. A processor can claim the annotations it processes, in which case no further attempt is made to find any processors for those annotations. After all of the annotations are claimed, the compiler does not search for additional processors.

If any processors generate new source files, then another round of annotation processing occurs: Any newly generated source files are scanned, and the annotations processed as before. Any processors called on previous rounds are also called on all subsequent rounds. This continues until no new source files are generated.

After a round occurs where no new source files are generated, the annotation processors are called one last time, to give them a chance to complete any remaining work. Finally, unless the -proc:only option is used, the compiler compiles the original and all generated source files.

Searching for Types

To compile a source file, the compiler often needs information about a type, but the type definition is not in the source files specified on the command line.

To compile a source file, the compiler often needs information about a type, but the type definition is not in the source files specified on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file, but that provide information through inheritance.

For example, when you create a subclass of java.awt.Window , you are also using the ancestor classes of Window : java.awt.Container , java.awt.Component , and java.lang.Object .

When the compiler needs type information, it searches for a source file or class file that defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath option.

If you set the -sourcepath option, then the compiler searches the indicated path for source files. Otherwise, the compiler searches the user class path for both class files and source files.

You can specify different bootstrap or extension classes with the -bootclasspath and the -extdirs options. See Cross-Compilation Options for javac.

A successful type search may produce a class file, a source file, or both. If both are found, then you can use the -Xprefer option to instruct the compiler which to use. If newer is specified, then the compiler uses the newer of the two files. If source is specified, the compiler uses the source file. The default is newer .

If a type search finds a source file for a required type, either by itself, or as a result of the setting for the -Xprefer option, then the compiler reads the source file to get the information it needs. By default the compiler also compiles the source file. You can use the -implicit option to specify the behavior. If none is specified, then no class files are generated for the source file. If class is specified, then class files are generated for the source file.

The compiler might not discover the need for some type information until after annotation processing completes. When the type information is found in a source file and no -implicit option is specified, the compiler gives a warning that the file is being compiled without being subject to annotation processing. To disable the warning, either specify the file on the command line (so that it will be subject to annotation processing) or use the -implicit option to specify whether or not class files should be generated for such source files.

Источник

Оцените статью