简体   繁体   中英

How to call a class from another project in Eclipse?

I'm using Eclipse and I have two different projects: A and B.

In project A , I have a class classA where I need to call a method methodB() from a class classB contained in the project B , how can I do that?

I've tried adding the project B to project A build path, but still doesn't work.

Thanks.

您需要在“项目”选项卡中添加另一个项目,或在“库”选项卡中添加该项目的类文件夹,即您可以尝试将项目B添加到项目A使用的运行配置中。转到菜单Run -> Run configurations ,则可以将项目B添加到运行配置的“类路径”标签中。

Here's an example that you may find helpful:

Project_1 has the following class:

ClassProjectOne.java which consists of:

public class ClassProjectOne {

    private int m_Age;
    private final int AGE_INPUT = 15;

    public ClassProjectOne() {
        setAge(AGE_INPUT);
    }

    public int getAge() {
        return m_Age;
    }

    private void setAge(int age) {
        m_Age = age;
    }
}

Project_2 has the following class:

ClassProjectTwo.java which consists of:

public class ClassProjectTwo {

    public static void main(String[] args) {
        ClassProjectOne t = new ClassProjectOne();
        System.out.println(t.getAge());
    }

}

In order for this to work, you must right click Project_2 and click on Properties . Then click on Java Build Path -> Add... -> Select Project_1 -> OK . This sets a Java Build Path.

If your class is static there is no need to initialize a new instance of it.

Hope this helps.

I've just done what you're trying to do. I called my first project 'project1'. In this projects i have a package called 'package1' which in turn contains a class called 'Class1' containing a (public) static method called 'staticMethod'. I called my second project 'project2' with a class 'Class2' in 'package2'. I added project1 to the build path of project2 and then inserted the statement import package1.Class1 at the beginning of the class Class2.

Put the Project B on the Build path, then do a Clean project from Project Menu option and then use it.

Click in "A" --> Properties --> Build Path --> Projects ---> Add the Project ---> Ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM