简体   繁体   English

如何从Eclipse中的另一个项目中调用类?

[英]How to call a class from another project in Eclipse?

I'm using Eclipse and I have two different projects: A and B. 我正在使用Eclipse,并且有两个不同的项目:A和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? 项目A中 ,我有一个类classA ,需要从项目B中包含的类classB调用方法methodB() ,该怎么办?

I've tried adding the project B to project A build path, but still doesn't work. 我尝试将项目B添加到项目A的构建路径中,但仍然无法正常工作。

Thanks. 谢谢。

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

Here's an example that you may find helpful: 这是一个可能对您有所帮助的示例:

Project_1 has the following class: Project_1具有以下类别:

ClassProjectOne.java which consists of: ClassProjectOne.java包含:

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: Project_2具有以下类别:

ClassProjectTwo.java which consists of: ClassProjectTwo.java ,包含:

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 . 为了Project_2起作用,必须右键单击Project_2并单击Properties Then click on Java Build Path -> Add... -> Select Project_1 -> OK . 然后单击Java Build Path > Add... > Select Project_1 > OK This sets a Java Build Path. 这将设置一个Java构建路径。

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'. 我将第一个项目称为“ 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'. 在这个项目中,我有一个名为“ package1”的包,该包又包含一个名为“ Class1”的类,该类包含一个称为“ staticMethod”的(公共)静态方法。 I called my second project 'project2' with a class 'Class2' in 'package2'. 我用“ package2”中的类“ Class2”调用了第二个项目“ project2”。 I added project1 to the build path of project2 and then inserted the statement import package1.Class1 at the beginning of the class Class2. 我将project1添加到project2的构建路径,然后在类Class2的开头插入了import package1.Class1语句。

Put the Project B on the Build path, then do a Clean project from Project Menu option and then use it. 将项目B放在生成路径上,然后从“项目菜单”选项执行“清理项目”,然后使用它。

Click in "A" --> Properties --> Build Path --> Projects ---> Add the Project ---> Ok 单击“ A”->属性->构建路径->项目--->添加项目--->确定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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