如何在Java中的另一个项目中使用一个项目中的类?

时间:2018-12-10 17:22:50

标签: java maven class

基本上我有两个不同的项目,我需要从A类调用B类中的某些方法。

我试图制作一个B类的jar并将其放在A类的依赖项上,但这没用。

有没有办法做到这一点?

编辑:

B类:包含一个FTP用户实用程序:

package br.com.consiste.FtpConnector;

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPConnection {

    public FTPClient createConnection() {

        String server = System.getenv("FTP_HOST"); 
        String user = System.getenv("FTP_USER");
        String pass = System.getenv("FTP_PASSWORD");

        int port = 21;

        FTPClient ftpClient = new FTPClient();

        try {
            ftpClient.connect(server, port);
            showServerReply(ftpClient);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Operation failed. Server reply code: " + replyCode);
            }
            boolean success = ftpClient.login(user, pass);
            showServerReply(ftpClient);
            if (!success) {
                System.out.println("Could not login to the server");
            } else {
                System.out.println("LOGGED IN SERVER");

            }
        } catch (IOException ex) {
            System.out.println("Oops! Something wrong happened");
            ex.printStackTrace();
        }
        return ftpClient;
    }

    private static void showServerReply(FTPClient ftpClient) {
        String[] replies = ftpClient.getReplyStrings();
        if (replies != null && replies.length > 0) {
            for (String aReply : replies) {
                System.out.println("SERVER: " + aReply);
            }
        }
    }
}

我已经在同一项目的其他类上编写了这些方法。

基本上我想在类A中调用这些方法,例如FTPClient.getHost()或其他任何方法。

1 个答案:

答案 0 :(得分:0)

要使用其他项目的类,您可以:

  • 使用maven依赖项导入包含类的jar
  • 使用gradle依赖项导入包含类的jar
  • 导入包含类的jar,将其手动添加到类路径中
  • 导入包含类的jar,将其添加到现有的类路径(例如tomcat的目录lib)-请注意,在这种情况下,您无法从ide中看到该类,而只能在运行时查看(这是它的方式)例如,使用反射工作一个jdbc驱动程序)

显然,您必须使一个包含该类的罐子,并且该类必须具有正确的可见性修饰符。