Skip to main content

java的package与文件路径与编译

· 3 min read

写了很久的php的原生代码,对php相对路径自动加载这类坑的恐惧已经深入骨髓了.
java和golang也有类似的内容,对于写java没多久的我来说,先记录一下

关于类名和classpath的关系,oracle的文档有相关的描述

Class Path and Package Names

Java classes are organized into packages that are mapped to directories in the file system. But, unlike the file system, whenever you specify a package name, you specify the whole package name and never part of it. For example, the package name for java.awt.Button is always specified as java.awt.

For example, suppose you want the JRE to find a class named Cool.class in the package utility.myapp. If the path to that directory is /java/MyClasses/utility/myapp, then you would set the class path so that it contains /java/MyClasses. To run that application, you could use the following java command:

java -classpath /java/MyClasses utility.myapp.Cool When the application runs, the JVM uses the class path settings to find any other classes defined in the utility.myapp package that are used by the Cool class.

The entire package name is specified in the command. It is not possible, for example, to set the class path so it contains /java/MyClasses/utility and use the command java myapp.Cool. The class would not be found.

You might wonder what defines the package name for a class. The answer is that the package name is part of the class and cannot be modified, except by recompiling the class.

首先说编译: 查看javac 的帮助:

javac --help
Usage: javac <options> <source files>

javac 的参数是: javac+文件路径

举个例子: 现在在com的上一级目录上

下面是HelloWorld.java的代码

package com.helloworld;

public class HelloWorld
{
static public int m = 1;
public int i = 1;

}
# ls 
com
# tree
.
└── com
└── helloworld
└── HelloWorld.java

我要怎么编译com/hellowrld/HelloWorld.java下面的文件呢?

这么编译就可以了:

javac com/helloworld/*.java

然后看一下目录树,在下面多了一个class文件

# tree
.
└── com
└── helloworld
├── HelloWorld.class
└── HelloWorld.java

重新开始,我们看看-d 这个参数有什么用:

# mkdir classes
# tree
.
├── classess
└── com
└── helloworld
└── HelloWorld.java

那么我们编译之后会在设置的-d的目录里面添加相关目录:

# javac -d ./classes/    com/helloworld/*.java
# tree
.
├── classes
│   └── com
│   └── helloworld
│   └── HelloWorld.class
├── classess
└── com
└── helloworld
└── HelloWorld.java

相关阅读