Ниже находится мой каталог проектов. Я пытаюсь использовать Kitchen.jar (находится в папке libs) в качестве зависимости файла.
![directory](https://i.stack.imgur.com/OVkB9.png)
Ниже приведен мой файл build.gradle, в котором я пытаюсьвключите Kitchen.jar как зависимость.
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building a CLI application
id 'application'
}
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// This dependency is used by the application.
implementation 'com.google.guava:guava:27.1-jre'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile files('libs/Kitchen.jar')
}
application {
// Define the main class for the application
mainClassName = 'Kitchen.App'
}
Однако, когда я запускаю gradle build
, я получаю следующую ошибку, которая говорит мне, что файл Kitchen.jar не был импортирован правильно. «Food» - это класс в Kitchen.jar.
![enter image description here](https://i.stack.imgur.com/fTk3T.png)
Так выглядит класс Oven для некоторого контекста того, как выглядит метод insertFood
как.
package Kitchen;
/**
* This class models an oven appliance for cooking food.
*/
public class Oven {
private final int maxTemperature;
private int currentTemperature = 0;
/**
* Creates an Oven object with a default maximum temperature of 320 degrees Celsius
*/
public Oven() {
this(320);
}
/**
* Creates an Oven object with a specific maximum temperature
*
* @param maxTemperature The maximum temperature this oven can be set to. Cannot be a negative number.
* @throws IllegalArgumentException If the maxTemperature is negative
*/
public Oven(int maxTemperature) {
if (maxTemperature < 0) {
throw new IllegalArgumentException("Invalid temperature");
}
this.maxTemperature = maxTemperature;
}
/**
* Sets the current temperature of the oven to the given value
*
* @param temperature The temperature to set in degrees Celsius
* @throws IllegalArgumentException If the temperature is negative or higher than this oven's maximum temperature.
*/
public void setTemperature(int temperature) {
if (temperature < 0 || temperature > maxTemperature) {
throw new IllegalArgumentException("Invalid temperature");
}
this.currentTemperature = temperature;
}
/**
* Gets the current temperature (the oven has no heating or cooling times and changes temperatures instantly)
* @return The current temperature in degrees Fahrenheit
*/
public int getCurrentTemperature() {
return (currentTemperature * 9/5) + 32;
}
/**
* Gets the maximum temperature this oven can be set to
* @return The max temperature in degrees Celsius
*/
public int getMaxTemperature() {
return maxTemperature;
}
/**
* Adds an item of food to the oven, potentially changing its state.
*
* @param food The food to be added to the oven
* @param duration The length of time in minutes the food will be in the oven for
* @throws IllegalArgumentException If the food parameter is null, or if the duration is negative
*/
public void insertFood(Food food, int duration) {
if (null == food) {
throw new IllegalArgumentException("Food may not be null");
}
if (duration < 0) {
throw new IllegalArgumentException("Duration must be >= 0");
}
food.cook(currentTemperature, duration);
}
}
Точно так же, IDEA показывает похожую ошибку, как показано ниже.
![enter image description here](https://i.stack.imgur.com/LtPcD.png)
Я пытался вручную добавитьФайл Kitchen.jar как зависимость через окно «Структура проекта» (см. Ниже), и даже если он добавлен как зависимость согласно скриншоту, указанные выше ошибки сохраняются.
![enter image description here](https://i.stack.imgur.com/BVZGz.png)
Я также пробовал File -> Invalidating Caches / Restart;однако это не решает мою проблему.
Почему ни один из классов в моем файле Kitchen.jar, например "Food", не зарегистрирован в моем проекте Gradle?
Редактировать 1:
Я попытался 0xadecimal решение, как показано ниже, но, к сожалению, он все еще не компилируется, и Intellij выдает ту же ошибку о не разрешении символа «Food» вКласс духовки, как показано ниже.
![enter image description here](https://i.stack.imgur.com/eZ1Pz.jpg)
Редактировать 2:
Я попытался использовать предложение Лукаса Кёрфера в комментариях для использования implementation files(...)
;однако, я все еще получаю ошибку компиляции, и Intellij все еще кричит на меня (правая часть скриншота). Обратите внимание, что каждый раз, когда я меняю файл build.gradle, я запускаю зависимости, нажимая зеленую кнопку рядом с dependencies
, хотя я настроил свой Intellij на автоматическое обновление при изменении файла build.gradle
. Это означает, что проблема не должна быть в том, что в Intellij не обновляются зависимости.
![enter image description here](https://i.stack.imgur.com/xWP9A.jpg)