如何在Java中使用父目录中的类? [英] How to use a class from a parent directory in Java?

查看:166
本文介绍了如何在Java中使用父目录中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在 Foo.java 中有一个名为 Foo 的类,它将使用一个名为<$的类c $ c> Bar 在 ../ Bar.java 里面。当我做 javac Foo.java

解决方案

将您的类添加到类路径..

  javac -cpBar.class的路径Foo.java 

您需要在 Foo.java 还..更好地使用一个包,并将类路径提供给包含你的包的目录。这样你就可以为你的类提供不同的命名空间..



所以,如果您的软件包是: - pkg1.pkg2.Bar 并且您已将 .java 保存到一个名为 Demo 的目录,那么你的类路径应该包含路径,直到 Demo ..而且你的类实际上还有两个以下目录 pkg1 / pkg2 / Bar.class 里面演示目录..

 演示+ 
|
+ - B.java(`在包pkg1.pkg2下)
|
+ - pkg1 +
| |
| + - pkg2 +
| |
| + - B.class
|
+ - A.java(`无包装下) - 添加 - 导入pkg1.pkg2.B
|
+ - A.class(javac -cp.A.java) - 将在当前目录中搜索包pkg1.pkg2

即使在那里不需要,如果你的 B.class <,你可以用任何路径替换它/ code>在其他地方..


For example, I have a class called Foo inside Foo.java which will use a class called Bar inside ../Bar.java. Is there any way to make that work when I do javac Foo.java?

解决方案

Add your class to classpath..

javac -cp "path to your Bar.class" Foo.java

You will need to import that class in your Foo.java also.. Better use a package, and give the classpath till the directory containing your package..That way you will be able to give different namespaces to your classes..

So, if your package is: - pkg1.pkg2.Barand you have saved your .java to a directory named Demo, then your classpath should contain path till Demo.. And your classes will actually be under two more directory pkg1/pkg2/Bar.class inside Demo directory..

Demo+
    |
    +-- B.java (`Under package pkg1.pkg2)
    |
    +--pkg1+
    |      |
    |      +--pkg2+
    |             |
    |             +-- B.class
    |
    +-- A.java (`Under no package`) - Add - import pkg1.pkg2.B 
    |
    +-- A.class (javac -cp . A.java) - Will search the package pkg1.pkg2 in current directory

Even though . is not needed there, you can replace it with any path, if your B.class is somewhere else..

这篇关于如何在Java中使用父目录中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆