Getting started with Java Jars and Classes

From ben.goodacre.name/tech

Jump to: navigation, search

Contents

What is a Java Class?

A Java class is a branch of code which be referred to by the creation of new objects in Java. From a narrow point of view it can be called a sub, but a class is more flexible.

http://docs.oracle.com/javase/tutorial/java/concepts/class.html

What is a Java Jar

A jar is a collection of java code and metadata into an archive, normally a zip.

Working with classes and Jars

In this example a class for converting farenheit to celcius is created with java code that references it and is placed into a Jar:

package tconvert;
public class TempratureConvertorBean {
  private double celsius = 0.0;
  private double fahrenheit = 32.0;
  public double getCelsius() {
    return celsius;
  }
  public void setCelsius(double c) {
    celsius = c;
    fahrenheit = 1.8*c + 32.0;
  }
  public double getFahrenheit() {
    return fahrenheit;
  }
  public void setFahrenheit(double f) {
    fahrenheit = f;
    celsius = (f-32.0)/1.8;
  }
  public String getInfo() {
    return new String("Temp Convert Bean");
  }
}
$ jar tf tconvert.jar
META-INF/
META-INF/MANIFEST.MF
tconvert/
tconvert/TempratureConvertorBean.class
import tconvert.TempratureConvertorBean;
public class F2C {
   public static void main(String[] arg) {
      TempratureConvertorBean b = new TempratureConvertorBean();
      double f = 0.0;
      if (arg.length>0) f = Double.parseDouble(arg[0]);
      b.setFahrenheit(f);
      double c = b.getCelsius();
      System.out.println("Fahrenheit = "+f);
      System.out.println("Celsius = "+c);
      System.out.println(b.getInfo());
   }
}

At this point the jar file cannot be executed by itself as the class has to be called for it to become an executable jar. If an attempt to execute is attempted now the following error occurs:

$ java -jar tconvert.jar 60.0
Failed to load Main-Class manifest attribute from tconvert.jar

An attribute must be added to the manifest pointing to our code.

Creating executable Jars

For the above example:

Main-Class: F2C
$ jar uvmf fs_f2c.txt tconvert.jar F2C.class
updated manifest
adding: F2C.class(in = 956) (out= 578)(deflated 39%)
$ java -jar tconvert.jar 60.0
Fahrenheit = 60.0
Celsius = 15.555555555555555
Temp Convert Bean

See also: http://stackoverflow.com/questions/2591516/why-its-failed-to-load-main-class-manifest-attribute-from-jar-file

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox