How to call a class from another project in Eclips

2019-02-25 20:13发布

问题:

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.

回答1:

You need to add another project in "Project" tab, or add class folder of the project in "Libraries" tab ie you may try to add project B to the Run configuration used by project A. Go to the menu Run -> Run configurations, ther you can add the project B in the tab 'classpath' of your run configuration.



回答2:

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.



回答3:

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.



回答4:

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