Compiling java code windows

How to compile and run Java code in Visual Studio Code

I downloaded Visual Studio Code and installed the «Java Extension Pack» by Microsoft.

Afterwards I downloaded the jdk1.8.0_161 and created the required environment variables as described in the «Java Extension Pack» documentation.

I then created a new file with .java ending and wrote a simple «Hello World» test program.

But how can I now compile and run the code?

2 Answers 2

As a first step, try to compile your programm from te command line. E.g. How do I run a Java program from the command line on Windows? is a good start. You can run the commands directly in VSCode’s integrated terminal. Optionally, create a VS Code build task from that command to run builds with the build command.

To run/debug, create a launch config in the debug viewlet, for example:

Here are the overall steps:

  • Install the Java Extension Pack —> you did this already
  • Create a Java project: Ctrl + Shift + Enter and type «Java». Choose the option «Java: Create Java Project»
  • Modify the App.java class and save it: Ctrl + S

When you save it, VS Code automatically compiles the java files for you. In the bin/app directory you’ll see a file called «App.class». That’s the confirmation you need.

Edit: Running the project: To run the project, hit F5. VSCode will ask if you want to add a configuration. Choose «Java: Launch Program». Make sure you have App.java opened and hit F5 one more time. That’s it.

I noticed that VSCode does not deal well with packages, but that is for another question.

Создание, компиляция и выполнения Java программ

Ключевой момент: вы сохраняете исходный код Java программы в файл с расширением .java и компилируете его в файл с расширением .class. Файл .class выполняется виртуальной машиной Java.

Перед тем как программа может быть выполнена, её необходимо создать и скомпилировать. Если в вашей программе возникли ошибки компиляции, вам необходимо изменить программу, чтобы исправить их, а затем перекомпилировать её. Если в вашей программе возникли ошибки выполнения, или она не приводит к правильному результату, вам необходимо изменить программу, перекомпилировать её и запустить снова. Этот процесс и является созданием (разработкой) программы.

Для создания и редактирования исходного кода Java вы можете использовать любой текстовый редактор или IDE. Этот раздел демонстрирует, как создавать, компилировать и запускать программы Java из командной строки. В разделе «Компиляция и запуск Java программ в NetBeans» показано, как это делать в IDE на примере NetBeans.

Можно вообще обойтись без IDE, а писать исходный код в любом текстовом редакторе (например, в Notepad), а компилировать в командной строке.

Внимание: файл с исходным кодом должен иметь расширение .java и иметь в точности такое же имя, как и имя публичного (public) класса. Например, файл с исходным кодом:

должен называться Welcome.java, поскольку имя public класса – Welcome.

Компилятор Java преобразовывает файл с исходным кодом Java в файл с байткодом Java. Следующая команда компилирует Welcome.java:

Если нет синтаксических ошибок, компилятор генерирует файл байкода с расширением .class. Следовательно, приведённая выше команда генерирует файл с названием Welcome.class.

Чтобы иметь возможность компилировать и запускать программы, вы должны установить JDK. Как это сделать описано в инструкциях:

Язык Java – это высокоуровневый язык программирования, но байткод Java – это низкоуровневый язык. Байткод похож на машинные инструкции, но нейтрален к архитектуре (не зависит от архитектуры) и может запускаться на любой платформе, которая имеет виртуальную машину Java – Java Virtual Machine (JVM). В отличие от физической машины, виртуальная машина – это программа, которая интерпретирует байткод Java. Это одно из главных преимуществ Java: байткод Java может работать на различных аппаратных платформах и операционных системах. Исходный код Java компилируется в байткод Java, а байткод Java интерпретируется виртуальной машиной Java. Ваш код Java может использовать код библиотеки Java. JVM выполняет ваш код вместе с кодом из библиотеки.

Выполнить Java программу – это значит запустить байткод программы. Вы можете выполнить байткод на любой платформе с JVM, которая является интерпретатором. Она (виртуальная машина Java) переводит отдельные инструкции байткода в целевой машинный языковой код. Это делается последовательно – одна инструкция за раз, а не вся программ за один присест. Каждый шаг немедленно выполняется, сразу после перевода.

Следующая команда выполняет байткод для программы, которая приведена выше:

На скриншоте ниже показан процесс компиляции и запуска:

Внимание: не используйте расширение .class в команде, когда запускаете программу. Используйте ИмяКласса для запуска программы. Если вы в командной строке используете ИмяКласса.class, то система будет пытаться работать с файлом ИмяКласса.class.class.

Справка: когда выполняется Java программа, JVM начинает с загрузки байткода класса в память, используя программу под названием загрузчик классов (class loader). Если ваша программа использует другие классы, загрузчик классов динамически подгружает их перед тем, как они понадобятся. После загрузки класса, JVM использует программу под названием контролёр байткода (bytecode verifier) для проверки правильности байткода и проверки, что байткод не нарушает ограничений безопасности Java. Java обеспечивает строгую защиту, чтобы убедиться, что файлы классов Java не подделаны и не вредят вашему компьютеру.

Педагогическое примечание: ваш инструктор может требовать от вас использовать пакеты для организации программ. Например, все программы из этой части можно поместить в пакет chapter2. Подробности о пакетах и пространствах имён будут рассмотрены далее. Также посмотрите раздел «Почему NetBeans всегда использует package».

Типичные ошибки компиляции и запуска Java программ

Команда javac не найдена

Если при запуске javac, т.е. при попытке компиляции Java программы вы получаете ошибку:

Это означает, что JDK не установлен. Либо установлен, но не настроены переменные окружения. Способы исправления очевидны:

  • установить JDK
  • настроить переменные окружения

Если JDK установлен, то можно обойтись без добавления переменной окружения. Для этого используйте абсолютный путь до исполнимого файла javac:

Ошибка Class names are only accepted if annotation processing is explicitly requested

Если попытаться скомпилировать программу следующим образом:

то возникнет ошибка:

Причина ошибки в том – что вы забыли указать расширение файла .java.

Ошибка записи (error while writing)

Компиляция заканчивается ошибкой:

Причина ошибки в том, что у компилятора (javac) недостаточно прав на запись в тот каталог, куда он пытается сохранить новый файл .class. Чтобы ошибка исчезла: предоставьте компилятору дополнительные права (запустите от имени администратора), либо сохраняйте в папку, на которую у текущего пользователя имеются права записи.

Ошибка «class is public, should be declared in a file named»

который заканчивается примерной такой ошибкой

означает, что вы неправильно назвали класс в исходном коде программы. Имя класса должно совпадать с именем файла. В данном случае файл называется Welcome.java, а класс внутри программы назван Welcomee

Error: Could not find or load main class

Если попытаться запустить программу следующим образом:

то возникнет ошибка

Причина её в том, что не нужно было добавлять к названию файла расширение .class. Виртуальная машина автоматически добавляет расширение и в приведённом примере она ищет файл Welcome.class.class

Ошибка Error: Could not find or load main class при запуске Java программы по абсолютному пути

Эта ошибка возможно при запуске Java программы по абсолютному пути:

Ошибка возникает как в Windows, так и в Linux:

Если в терминале вы находитесь в той же директории, что и файл, который вы запускаете, то не нужно указывать абсолютный путь. Например, нужно запускать так:

Если же вы находитесь в другой директории, то нужно использовать опцию -cp, после которой указать путь до каталога, где размещена запускаемая программа. А далее указать запускаемый файл без расширения .class:

Как видно из скриншота, командная строка находится в папке C:\WINDOWS\system32. Файл, который нам нужно запустить, находится в папке C:\ (корень диска). Мы указываем после ключа -cp папку C:\, а затем пишем имя файла программы без расширения – Welcome.

Аналогично нужно поступать в Linux. Пример команды:

Ошибка Main method not found in class

Если при запуске вы столкнулись с ошибкой:

Это означает, что вы не указали метод main, либо написали слово неправильно (например, Main вместо main).

Особенности компиляции и запуска Java программ в Windows

Команда «javac» не является внутренней или внешней командой, исполняемой программой или пакетным файлом

Эта ошибка рассмотрена чуть выше. Для установки и настройки переменных окружения в Windows обратитесь к инструкции «Установка Java (JDK) в Windows».

Проблема с кодировкой в Java программах в командной строке Windows

Если вы написали программу, которая выводит кириллицу в консоль:

А в качестве результата получили крякозяблы:

Значит кодировка, в которой выводит строки ваша программа, отличается от кодировки командной строки Windows.

Имеется несколько способов исправить эту проблему. Кстати, если для запуска консольных программ Java вы используете NetBeans, то он выводит строки в правильной кодировке. В Linux эта проблема также отсутствует. Если вам нужно поменять кодировку на время, то вы можете выполнить следующие команды:

Читайте также:  Как установить windows с папки с файлами

Для того, чтобы смена кодировки командной строки Windows не сбрасывалась после закрытия и открытия командной строки, можно внести изменения в реестр Windows. Для этого нажмите Win+x, выберите «Выполнить», в открывшееся окно введите regedit. В открывшейся программе (редактор реестра Windows) перейдите к [HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\Autorun] и измените (или добавьте) значение на @chcp 65001>nul

javac — Java programming language compiler

SYNOPSIS

Arguments may be in any order.

options Command-line options. sourcefiles One or more source files to be compiled (such as MyClass.java). classes One or more classes to be processed for annotations (such as MyPackage.MyClass). @argfiles One or more files that lists options and source files. The -J options are not allowed in these files.

DESCRIPTION

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

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

  • For a small number of source files, simply list the file names on the command line.
  • For a large number of source files, list the file names in a file, separated by blanks or line breaks. Then use the list file name on the javac command line, preceded by an @ character.

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 .

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

You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in C:\workspace, the source code for com.mysoft.mypack.MyClass should be in C:\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 -d (see Options, below).

OPTIONS

The compiler has a set of standard options that are supported on the current development environment and will be supported in future releases. An additional set of non-standard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Non-standard options begin with -X.

Standard Options

If the -sourcepath option is not specified, the user class path is also searched for source files.

If the -processorpath option is not specified, the class path is also searched for annotation processors.

-Djava.ext.dirs=directories Override the location of installed extensions. -Djava.endorsed.dirs=directories Override the location of endorsed standards path. -d directory Set the destination directory for class files. The directory must already exist; javac will not create it. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d C:\myclasses and the class is called com.mypackage.MyClass , then the class file is called C:\myclasses\com\mypackage\MyClass.class .

If -d is not specified, javac puts each class files in the same directory as the source file from which it was generated.

Note: The directory specified by -d is not automatically added to your user class path.

-deprecation Show a description of each use or override of a deprecated member or class. Without -deprecation, javac shows a summary of the source files that use or override deprecated members or classes. -deprecation is shorthand for -Xlint:deprecation. -encoding encoding Set the source file encoding name, such as EUC-JP and UTF-8 . If -encoding is not specified, the platform default converter is used. -endorseddirs directories Override the location of endorsed standards path. -extdirs directories Overrides the location of the ext directory. The directories variable is a colon-separated list of directories. Each JAR archive in the specified directories is searched for class files. All JAR archives found are automatically part of the class path.

If you are cross-compiling (compiling classes against bootstrap and extension classes of a different Java platform implementation), this option specifies the directories that contain the extension classes. See Cross-Compilation Options for more information.

-g Generate all debugging information, including local variables. By default, only line number and source file information is generated. -g:none Do not generate any debugging information. -g: Generate only some kinds of debugging information, specified by a comma separated list of keywords. Valid keywords are: source Source file debugging information lines Line number debugging information vars Local variable debugging information -help Print a synopsis of standard options. -implicit: Controls the generation of class files for implicitly loaded source files. To automatically generate class files, use -implicit:class. To suppress class file generation, use -implicit:none. If this option is not specified, the default is to automatically generate class files. In this case, the compiler will issue a warning if any such class files are generated when also doing annotation processing. The warning will not be issued if this option is set explicitly. See Searching For Types. -Joption Pass option to the java launcher called by javac. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.

Note: CLASSPATH, -classpath, -bootclasspath, and -extdirs do not specify the classes used to run javac. Fiddling with the implementation of the compiler in this way is usually pointless and always risky. If you do need to do this, use the -J option to pass through options to the underlying java launcher.

-nowarn Disable warning messages. This has the same meaning as -Xlint:none. -proc: Controls whether annotation processing and/or compilation is 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. -processorpath path Specify where to find annotation processors; if this option is not used, the class path will be searched for processors. -s dir Specify the directory where to place generated source files. The directory must already exist; javac will not create it. If a class is part of a package, the compiler puts the source file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -s C:\mysrc and the class is called com.mypackage.MyClass , then the source file will be placed in C:\mysrc\com\mypackage\MyClass.java . -source release Specifies the version of source code accepted. The following values for release are allowed: 1.3 The compiler does not support assertions, generics, or other language features introduced after Java SE 1.3. 1.4 The compiler accepts code containing assertions, which were introduced in Java SE 1.4. 1.5 The compiler accepts code containing generics and other language features introduced in Java SE 5. 5 Synonym for 1.5. 1.6 No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors instead of warnings as in previous releases of Java SE. 6 Synonym for 1.6. 1.7 This is the default value. The compiler accepts code with features introduced in Java SE 7. 7 Synonym for 1.7. -sourcepath sourcepath Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives. If packages are used, the local path name within the directory or archive must reflect the package name.

Note: Classes found through the class path may be subject to automatic recompilation if their sources are also found. See Searching For Types.

-verbose Verbose output. This includes information about each class loaded and each source file compiled. -version Print version information. -Werror Terminate compilation if warnings occur. -X Display information about non-standard options and exit.

Cross-Compilation Options

By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath and -extdirs when cross-compiling; see Cross-Compilation Example below.

-target version Generate class files that target a specified version of the VM. Class files will run on the specified target and on later versions, but not on earlier versions of the VM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7).

The default for -target depends on the value of -source:

  • If -source is not specified, the value of -target is 1.7
  • If -source is 1.2, the value of -target is 1.4
  • If -source is 1.3, the value of -target is 1.4
  • If -source is 1.5, the value of -target is 1.7
  • If -source is 1.6, the value of -target is 1.7
  • For all other values of -source, the value of -target is the value of -source.
Читайте также:  Восстановление спящего режима windows 10

-bootclasspathbootclasspath Cross-compile against the specified set of boot classes. As with the user class path, boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives.

Non-Standard Options

Warnings That Can Be Enabled or Disabled with -Xlint Option

Enable warning name with the option -Xlint:name, where name is one of the following warning names. Similarly, you can disable warning name with the option -Xlint:-name:

cast Warn about unnecessary and redundant casts. For example: classfile Warn about issues related to classfile contents. deprecation Warn about use of deprecated items. For example:

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

dep-ann Warn about items that are documented with an @deprecated Javadoc comment, but do not have a @Deprecated annotation. For example: divzero Warn about division by constant integer 0. For example: empty Warn about empty statements after if statements. For example: fallthrough Check switch blocks for fall-through cases and provide 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 does not 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 does not end with a break statement:

If the -Xlint:fallthrough flag were used when compiling this code, the compiler would emit a warning about «possible fall-through into case,» along with the line number of the case in question.

finally Warn about finally clauses that cannot complete normally. For example:

The compiler generates a warning for finally block in this example. When this method is called, it returns a value of 0 , not 1 . A finally block always executes when the try block exits. In this example, if control is transferred to the catch , then the method exits. However, the finally block must be executed, so it is executed, even though control has already been transferred outside the method.

options Warn about issues relating to the use of command line options. See Cross-Compilation Example for an example of this kind of warning. overrides Warn about issues regarding 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, which matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod . Consequently, this example compiles.

path Warn about invalid path elements and nonexistent path directories on the command line (with regards to the class path, the source path, and other paths). Such warnings cannot be suppressed with the @SuppressWarnings annotation. For example: processing Warn about issues regarding annotation processing. The compiler generates this warning if you have a class that has an annotation, and you use an annotation processor that cannot handle that type of exception. For example, the following is a simple annotation processor:

Source file AnnoProc.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 .

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

The following does not generate a rawtypes warning:

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

serial Warn about missing serialVersionUID definitions on serializable classes. For example:

The compiler generates the following warning:

If a serializable class does not explicitly declare a field named serialVersionUID , then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values because the default process of computing serialVersionUID vales is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

static Warn about issues relating to use of statics. For example:

The compiler generates the following warning:

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

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

try Warn about issues relating to 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 statement is not used: unchecked Give 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 variable ls has the parameterized type List . When the List referenced by l is assigned to ls , the compiler generates an unchecked warning; the compiler is unable to determine at compile time, and moreover knows that the JVM will not be able to determine at runtime, if l refers to a List type; it does not. Consequently, heap pollution occurs.

In detail, 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 backwards compatibility with versions of Java SE that do not 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 .

varargs Warn about unsafe usages of variable arguments (varargs) methods, in particular, those that contain non-reifiable arguments. For example:

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 does not 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 is a possibility of heap pollution.

COMMAND LINE ARGUMENT FILES

To shorten or simplify the javac command line, you can specify one or more files that themselves contain arguments to the javac command (except -J options). This enables you to create javac commands of any length on any operating system.

An argument file can include javac options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. If a filename contains embedded spaces, put the whole filename in double quotes, and double each backslash ( «My Files\\Stuff.java» ).

Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java ). Use of the ‘@‘ character to recursively interpret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

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

Example — Single Arg 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 the next example.

Example — Two Arg Files

You can create two argument files — one for the javac options and the other for the source filenames: (Notice the following lists have no line-continuation characters.)

Create a file named » options » containing:

Create a file named » classes » containing:

You would then run javac with:

Example — Arg Files with Paths

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

Читайте также:  Mac os sierra курсоры

ANNOTATION PROCESSING

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

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

Overview of annotation processing

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 it is not given, 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 will be invoked. A processor may «claim» the annotations it processes, in which case no further attempt is made to find any processors for those annotations. Once all annotations have been claimed, the compiler does not look for additional processors.

If any processors generate any new source files, another round of annotation processing will occur: any newly generated source files will be scanned, and the annotations processed as before. Any processors invoked on previous rounds will also be invoked 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 will be invoked one last time, to give them a chance to complete any work they may need to do. Finally, unless the -proc:only option is used, the compiler will compile the original and all the generated source files.

Implicitly loaded source files

To compile a set of source files, the compiler may need to implicitly load additional source files. (See Searching For Types). Such files are currently not subject to annotation processing. By default, the compiler will give a warning if annotation processing has occurred and any implicitly loaded source files are compiled. See the -implicit option for ways to suppress the warning.

SEARCHING FOR TYPES

When compiling a source file, the compiler often needs information about a type whose definition did not appear in the source files given 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 which provide information through inheritance.

For example, when you subclass java.applet.Applet, you are also using Applet’s ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.lang.Object.

When the compiler needs type information, it looks for a source file or class file which 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 command line option. (For details, see Setting the Class Path).

If you set the -sourcepath option, 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 -extdirs options; see Cross-Compilation Options below.

A successful type search may produce a class file, a source file, or both. If both are found, you can use the -Xprefer option to instruct the compiler which to use. If newer is given, the compiler will use the newer of the two files. If source is given, it will use 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 -Xprefer, the compiler will read the source file to get the information it needs. In addition, it will by default compile the source file as well. You can use the -implicit option to specify the behavior. If none is given, no class files will be generated for the source file. If class is given, class files will be generated for the source file.

The compiler may not discover the need for some type information until after annotation processing is complete. If the type information is found in a source file and no -implicit option is given, the compiler will give 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.

PROGRAMMATIC INTERFACE

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

Example

To perform a compilation using arguments as you would give on the command line, you can use the following:

This will write any diagnostics to the standard output stream, and return the exit code that javac would give when invoked from the command line.

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

Old Interface

Note: This API is retained for backwards compatibility only; all new code should use the Java Compiler API, described above.

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

The args parameter represents any of the command line arguments that would normally be passed to the javac program and are outlined in the above Synopsis section.

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

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

Note that all other classes and methods found in a package whose name starts with com.sun.tools.javac (informally known as sub-packages of com.sun.tools.javac ) are strictly internal and subject to change at any time.

EXAMPLES

Compiling a Simple Program

The following source file, C:\greetings\Hello.java , defines a class called greetings.Hello:

The greetings directory is the package directory both for the source file and the class file and is off the current directory. This allows us to use the default user class path. It also makes it unnecessary to specify a separate destination directory with -d.

Compiling Multiple Source Files

This example compiles all the source files in the package greetings .

Specifying a User Class Path

Having changed one of the source files in the previous example, we recompile it:

Since greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The example above works, because our default user class path happens to be the directory containing the package directory. But suppose we want to recompile this file and not worry about which directory we’re in? Then we need to add \examples to the user class path. We can do this by setting CLASSPATH, but here we’ll use the -classpath option.

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

To execute a class in greetings , we need access both to greetings and to the classes it uses.

Separating Source Files and Class Files

It often makes sense to keep source files and class files in separate directories, especially on large projects. We use -d to indicate the separate class file destination. Since the source files are not in the user class path, we use -sourcepath to help the compiler find them.

Note: The compiler compiled src\farewells\Base.java , even though we didn’t specify it on the command line. To trace automatic compiles, use the -verbose option.

Cross-Compilation Example

The following example uses javac to compile code that will run on a 1.6 VM.

The -source 1.6 option specifies that version 1.6 (or 6) of the Java programming language be used to compile OldCode.java . The option -target 1.6 option ensures that the generated class files will be compatible with 1.6 VMs. Note that in most cases, the value of the -target option is the value of the -source option; in this example, you can omit the -target option.

You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, the compiler generates a warning:

If you do not specify the correct version of bootstrap classes, the compiler will use the old language rules (in this example, it will use version 1.6 of the Java programming language) combined with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 6) because reference to non-existent methods can get included.

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