Java 打包信息
在 java 中,可以在打包是往包里添加包的版本等基本信息,这有助于各版本包之间的协调,在分布式系统中也适用。
在 java 包中添加基本信息有两种方式,一是传统的往包的 MANIFEST.MF 文件中写信息,二是用注解。
1,往 MANIFEST.MF 写信息,包括:
Name The name of the specification.Specification-Title The title of the specification.Specification-Version The version of the specification.Specification-Vendor The vendor of the specification.Implementation-Title The title of the implementation.Implementation-Version The build number of the implementation.Implementation-Vendor The vendor of the implementation.
Name: java/util/Specification-Title: Java Utility ClassesSpecification-Version: 1.2Specification-Vendor: Sun Microsystems, Inc.Implementation-Title: java.utilImplementation-Version: build57Implementation-Vendor: Sun Microsystems, Inc.
PackagemyPackage = Test.class.getPackage();myPackage.getImplementationVersion()...
@Annotation1(...)package sample;
package sample;@Annotation1(...)abstract interface package-info{}应用程序调用 Package 的 getAnnotation 方法 /** * @throws NullPointerException {@inheritDoc} * @since 1.5 */ public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return getPackageInfo().getAnnotation(annotationClass); }getAnnotation 方法再通过 getPackageInfo() 获得由编译器根据 package-info.java 文件产生的 package-info 接口,从而可以获得所有注解信息 private Class<?> getPackageInfo() { if (packageInfo == null) { try { packageInfo = Class.forName(pkgName + ".package-info", false, loader); } catch (ClassNotFoundException ex) { // store a proxy for the package info that has no annotations class PackageInfoProxy {} packageInfo = PackageInfoProxy.class; } } return packageInfo; }注解类:SampleAnnot.java,该类只有一个 field,就是 versionpackage sample;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.PACKAGE)public @interface SampleAnnot {String version();}-------------------------package-info.java:该文件只有一行包的声明语句和一行注解@SampleAnnot(version="1.0")package sample;-------------------------Test.java:该文件获取包对象,并从包对象中获取包的注解信息,关于获取过程请参照上面源码分析package sample;public class Test {/** * @param args */public static void main(String[] args) {// 获取 SampleAnnot 注解SampleAnnot sampleAnnot = Test.class.getPackage().getAnnotation(SampleAnnot.class);// 打印版本信息System.out.println(sampleAnnot.version());}}